4.3.1 clear_contents()函数和clear()函数–清楚单元格的内容和格式
表达式.clear_contents()
- Range对象的clear_contects()函数用于清除单元格的内容,但不会清除单元格的格式设置
表达式.clear()
- Range对象的clear()用于清楚单元格的内容和格式设置。
import xlwings as xw
app = xw.App(visible=False, add_book=False)
workbook = app.books.open('./example.xlsx)
worksheet = workbook.sheets[sheet1']
worksheet.range('A4:B4').clear_contents()
worksheet.range('A4:B4').clear()
workbook.save()
workbook.close()
app.quit()
4.3.2 value()属性–读取或输入数据
表达式.value
- Range对象的value属性用于返回指定单元格区域中的数据,通过对该属性赋值则可在单元格区域中输入数据。
import xlwings as xw
app = xw.App(visible=False, add_book False)
workbook = app.books.open('./example.xlsx')
worksheet = woekbook.sheets['sheet1']
data1 = wprksheet.range('B5').value
print(data1)
workbook.close()
app.quit()
4.3.3 formula属性–读取或输入公式
表达式.formula
- Range对象的formula属性用于返回指定单元格区域中的公式,通过为该属性赋值则可在单元格区域中输入公式。
import xlwings as xw
app = xw.App(visible=False, add_bokk=False)
workbook = app.books.open('./example.xlsx')
worksheet = workbook.sheets['sheet1']
rng = worksheet.range('B2').expand('table')
for r in rng.rows:
row_address= get_address(row_absolute=False,column_absolute=False)
row_formula = =f'=SUM({row_addr})'
cell = r.last_cell.offset(column_offset=1)
cell.formula = row_formula
for c in rng.columns:
col_adrr = c.get_address(row_absolute=False, column_absolute=False)
col_formula = f'=AVERAGE({col_addr})'
cell = c.last_cell.offset(row_offset=1)
cell.formula = col_formula
workbook.save('./other.xlsx')
workbook.close()
app.quit()
4.3.4 merge()函数和unmerge()函数–合并和拆分单元格
表达式.merge(across)/unmerge()
- Range对象的merge(across)和unmerge()函数分别用于完成合并单元格和取消合并单元格
- across:用于设置是否将单元格区域中的每一行单元格分别合并。如果设置为False或省略该参数,表示不分别合并每一行单元格;如果设置为True,则表示分别合并每一行单元格。
import xlwings as xw
app = xw.App(visible=False, add_boOK=False)
workbook = app.books.open('./example.xlsx')
workbooksheet = workbook.sheets[0]
worksheet.range('A1:E1').merge()
workbook.save('./other.xlsx')
workbook.close()
app.quit()
4.3.5 copy()函数–复制单元格
表达式.copy(destination)
- copy函数用于复制单元格区域
- destination:通常设置成另一个Range对象,代表赋值操作的目标位置。如果省略该参数,表示将所选单元格区域复制到剪贴板。
import xlwings as xw
app = xw.APP(visible=False, add_book=False)
book_src = app.books.open('./example.xlsx')
book_des = app.books.add()
sheet_des = book_des.sheets[0]
column_title = book.src.sheets[0].range('A1').expand('right')
column_title.copy(destination=sheet_des.range('A1'))
for i in book_src.sheets:
data_src = i.range('A2').expand('table')
data_des = sheer_des.range('A1').expand('down').last_cell.offset(row_offset=1)
data_src.copy(destination=data_des)
book_src.close()
sheet_des.autofit()
book_des.save('./other.xlsx')
app.quit()