4.2.1 adress属性和get_adress()函数–获取单元格区域的地址
表达式.adress:用于获取单元格区域的绝对引用地址;
表达式.get_adress(row_absolute, column_absolute,include_sheetname,external):Range对象的get_adress()函数用于按照指定格式返回单元格区域的地址,如绝对引用,相对引用,混合引用等格式的地址。
- row_absolute:是否对地址中的行号使用绝对引用格式。设置为True或省略表示使用绝对引用格式,设置为False表示设置为相对引用格式。
- column——absolute:是否对地址中的列标使用绝对引用格式;设置为True或省略表示使用绝对引用格式,设置为False表示设置为相对引用格式。
- include_sheetname:是否在地址中包含工作表名称。设置为True表示包含,设置为False表示不包含。如果external参数设置为True,将忽略此参数。
- external:是否在地址中包含工作薄名称和工作表名称。
# 获取单元格区域的地址
import xlwings as xw
app = xw.App(visible=False, add_book=False)
workbook = app.books.open('./example.xlsx')
worksheet = woekbook.sheets['example1']
rng = worksheet.range('A10:D20')
addr1 = rng.addres
addr2 = rng.get_adress(row_absolute=False, column_absolute=False)
addr3 = rng.get_adress(row_absolute=True, column_absolute=False)
addr4 = rng.get_adress(include_sheetname=True)
addr5 = rng.get_adress(external=True)
print(addr1, addr2, addr3)
print(addr4)
print(addr5)
workbook.close()
app.quit()
# 输出
$A$10:$D$20 A10:D20 A$10:D$20
example1!$A$10:$D$20
[example.xlsx]example1!$A$10:$D$20
4.2.2 row属性和column属性–获取单元格的行号和列号
Range对象的row属性和column属性分别用于返回指定单元格的行号和列号。
表达式.row/column
import xlwings as xw
app = xw.App(visible=False, add_book=False)
workbook = app.books.open('./example.xlsx')
worksheet = woekbook.sheets['example1']
rng = worksheet.range('A1').expand('table').last_cell
row_num = rng.row
column_num = rng.column
print(row_num ,column_num)
workbook.close()
app.quit()
4.2.3 count属性–获取单元格区域的单元格数于行/列数
import xlwings as xw
app = xw.App(visible=False, add_book=False)
workbook = app.books.open('./example.xlsx')
worksheet = woekbook.sheets['example1']
rng = worksheet.range('A1').expand('table')
cell_nums = rng.count
row_num = rng.row.count
column_num = rng.column.count
print(cell_nums,row_num ,column_num)
workbook.close()
app.quit()
4.2.4 shape属性–获取单元格区域的行/列数
import xlwings as xw
app = xw.App(visible=False, add_book=False)
workbook = app.books.open('./example.xlsx')
worksheet = woekbook.sheets['example1']
r_shape = worksheet.range('A1').expand('table').shape
row_num = r_shape[0]
column_num = r_shape[1]
print(r_shape)
print(row_num ,column_num)
workbook.close()
app.quit()
# 输出
(32, 4)
32 4
4.2.5 width属性和height属性–获取单元格区域的宽度和高度
import xlwings as xw
app = xw.App(visible=False, add_book=False)
workbook = app.books.open('./example.xlsx')
worksheet = woekbook.sheets['example1']
area = worksheet.range('A1').expand('table')
a = area.width
b = area.height
print(a, b)
workbook.close()
app.quit()