xlwings 安裝
xlwings 打開-新建
import time
import xlwings as xw
"""
visible
Ture:可見excel
False:不可見excel
add_book
True:打開excel并且新建工作簿
False:不新建工作簿
"""
app = xw.App(visible=True, add_book=False)
wb = app.books.open('./a.xlsx')
wb2 = app.books.open("./b.xlsx")
# 打印當(dāng)前活躍的books-<Book [b.xlsx]>
print(app.books.active)
# 打印當(dāng)前的book-Books([<Book [a.xlsx]>, <Book [b.xlsx]>])
print(app.books)
wb.save()
# 關(guān)閉a.xlsx文件-指定操作的excel
# wb.close()
app.books[0].close()
time.sleep(3)
app.quit()
import xlwings as xw
app = xw.App(visible=True, add_book=False)
# 添加一個(gè)新的工作薄
wb = app.books.add()
# 保存文件
wb.save('./a2.xlsx')
wb.close()
app.quit()
xlwings sheet-api
wb.sheets.add("sheet2")
wb.sheets["sheet2"].delete()
wb.sheets[1].name
wb.sheets[1].name=“abc”
wb.sheets[1].clear()
wb.sheets.active
sh = wb.sheets.active
sh.range("A1").value="A1"
wb.sheets["sheet1"].activate()
xlwings 操作數(shù)據(jù)
import xlwings as xw
import time
app = xw.App(visible=True, add_book=False)
wb = app.books.open("./a.xlsx")
sht = wb.sheets["sheet1"]
# TODO 待輸入-見下面示例
# A1 單元格
wb.sheets["sheet1"].range("A1")
# A2 單元格
sht.range("A2")
# A3單元格-xw-當(dāng)前活躍的app-book-sheet
xw.Range("A3")
# A4單元格
rng_a4 = sht["A4"]
# A1:B3 單元格
rng_a1_b3 = sht["A1:B3"]
rng_a1_b3_2 = sht.range("A1:B3")
xw.Range((1, 1), (3, 2))
# C1單元格
rng_c1 = sht[0, 2]
time.sleep(3)
wb.save()
wb.close()
app.quit()
- 單個(gè)單元格輸入
sht.range("A1").value="A1"
- 輸入行-- 在A2輸入1,B2輸入2
sht.range("A2").value=[1,2]
- 輸入行-A3-A4-A5賦值
sht.range("A3").options(transpose=True).value = ["行", "行", "行"]
- 輸入表格
sht.range('A4').options(expand='table').value = [[1, 2], [3, 4]]
sht.range("A4:B5").value = [[1, 2], [3, 4]]
xlwings 讀取數(shù)據(jù)
sht.range("A1").value
sht.range("A1:A3").value
sht.range("A1:B3").value
xw.Range("A1").value
|