新建
import xlwings as xw
app = xw.App(visible=True, add_book=False)
wb = app.books.add()
wb.sheets['sheet1'].range('A1').value = "生而为人"
wb.save(r'D:/xltest.xls')
wb.close()
app.quit()
print("完成")
打开
import xlwings as xw
app = xw.App(visible=True, add_book=False)
app.display_alerts = False
app.screen_updating = False
filepath = r'D:/test_xlwings.xls'
wb = app.books.open(filepath)
wb.save()
wb.close()
time.sleep(5)
app.quit()
print("完成")
修改
import xlwings as xw
app = xw.App(visible=True, add_book=False)
wb = app.books.open(r'D:/xltest.xls')
wb.sheets['sheet1'].range('A2').value = "我很抱歉"
wb.save()
wb.close()
app.quit()
引用
import xlwings as xw
app = xw.App(visible=True, add_book=False)
wb = app.books.open(r'D:/xltest.xls')
sht = wb.sheets['sheet1']
sht.range('A2').value = "hello"
sht.range("A1").value = [1,2,3]
sht.range('A1').options(transpose=True).value=[1,2,3]
sht.range('A1').options(expand = 'table').value = [[1,2],[3,4]]
sht.range('a1:d1').value = [1,2,3,4]
wb.save()
wb.close()
app.quit()
读取单个值
a = sht.range('A1').value
print(a)
book 常用api
import xlwings as xw
wb = xw.Book('test_xlwings.xls')
wb = xw.books.active
x= wb.fullname
print(x)
x=wb.name
print(x)
x=wb.save(path=None)
x=wb.close()
sheet常用api
sht=xw.books['工作簿名称'].sheets['sheet的名称']
sht.activate()
sht.clear()
sht.contents()
sht.name
sht.delete
sheet api 场景应用
import xlwings as xw
wb = xw.Book('test_xlwings.xls')
sht = wb.sheets['sheet1']
a = sht.range('A1').value
print(a)
sht.activate()
b = sht.name
print(b)
rng = sht.range('A1').expand('down')
rng.value = ['a1', 'a2', 'a3', 'a4', 'a5']
rng = sht.range('A1').expand('table')
rng.value = [['a1', 'a2', 'a3'], ['b1', 'b2', 'b3']]
wb.save()
range常用api
rng.column_width
rng.width
rng.hyperlink
rng.last_cell
rng.offset(row_offset=0,column_offset=0)
rng.resize(row_size=None,column_size=None)
rng.row
rng.autofit()
rng.row_height
rng.height
rng.shape
rng.sheet
rng.rows
rng.rows[0]
rng.rows.count
rng.columns
rng.columns[0]
rng.columns.count
rng=xw.Range('A1')
rng.address
rng.get_address()
rng.clear_contents()
rng.clear()
rng.color
rng.color=(255,255,255)
rng.color=None
rng.column
rng.count
rng.current_region
rng.end('down')
rng.formula='=SUM(B1:B5)'
rng.formula_array
rng.get_address(row_absolute=True, column_absolute=True,include_sheetname=False, external=False)
rng.columns.autofit()
rng.rows.autofit()
book工作簿合集的api
xw.books.add()
xw.books.active
sheet 工作合集的api
xw.sheets.add(name=None,before=None,after=None)
xw.sheets.active