200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > Python使用openpyxl读写excel文件

Python使用openpyxl读写excel文件

时间:2020-08-01 15:47:30

相关推荐

Python使用openpyxl读写excel文件

Python使用openpyxl读写excel文件

Python使用openpyxl读取excel文件中数据Python使用openpyxl往excel文件中写入数据

Python使用openpyxl读取excel文件中数据

openpyxl是一个第三方库,可以处理xlsx格式的Excel文件。

pip install openpyxl安装,(Aanconda自带)

读取Excel文件

需要导入相关函数。

from openpyxl import load_workbook

默认可读写,若有需要可以指定write_only和read_only为True

wb = load_workbook('mainbuilding33.xlsx')

默认打开的文件为可读写,若有需要可以指定参数read_only为True。

获取工作表–Sheet

获得所有sheet的名称

print(wb.get_sheet_names())

根据sheet名字获得sheet

a_sheet = wb.get_sheet_by_name('Sheet1')

获得sheet名

print(a_sheet.title)

获得当前正在显示的sheet, 也可以用wb.get_active_sheet()

sheet = wb.active

获取单元格

获取某个单元格的值,观察excel发现也是先字母再数字的顺序,即先列再行

b4 = sheet['B4']

分别返回

print(f'({b4.column}, {b4.row}) is {b4.value}') # 返回的数字就是int型

除了用下标的方式获得,还可以用cell函数, 换成数字,这个表示B4

b4_too = sheet.cell(row=4, column=2)print(b4_too.value)

b4.column返回B, b4.row返回4, value则是那个单元格的值。另外cell还有一个属性coordinate, 像b4这个单元格返回的是坐标B4。

获得最大列和最大行

print(sheet.max_row)print(sheet.max_column)

获取行和列

sheet.rows为生成器, 里面是每一行的数据,每一行又由一个tuple包裹。

sheet.columns类似,不过里面是每个tuple是每一列的单元格。

因为按行,所以返回A1, B1, C1这样的顺序

for row in sheet.rows:

for cell in row:

print(cell.value)

A1, A2, A3这样的顺序

for column in sheet.columns:

for cell in column:

print(cell.value)

上面的代码就可以获得所有单元格的数据。如果要获得某行的数据呢?给其一个索引就行了,因为sheet.rows是生成器类型,不能使用索引,转换成list之后再使用索引,list(sheet.rows)[2]这样就获取到第三行的tuple对象。

for cell in list(sheet.rows)[2]:

print(cell.value)

如何获得任意区间的单元格?

可以使用range函数,下面的写法,获得了以A1为左上角,B3为右下角矩形区域的所有单元格。注意range从1开始的,因为在openpyxl中为了和Excel中的表达方式一致,并不和编程语言的习惯以0表示第一个值。

for i in range(1, 4):for j in range(1, 3):print(sheet.cell(row=i, column=j))# out<Cell mainbuilding33.A1><Cell mainbuilding33.B1><Cell mainbuilding33.A2><Cell mainbuilding33.B2><Cell mainbuilding33.A3><Cell mainbuilding33.B3>

还可以像使用切片那样使用。sheet[‘A1’:‘B3’]返回一个tuple,该元组内部还是元组,由每行的单元格构成一个元组。

for row_cell in sheet['A1':'B3']:for cell in row_cell:print(cell)for cell in sheet['A1':'B3']:print(cell)# out(<Cell mainbuilding33.A1>, <Cell mainbuilding33.B1>)(<Cell mainbuilding33.A2>, <Cell mainbuilding33.B2>)(<Cell mainbuilding33.A3>, <Cell mainbuilding33.B3>)

根据字母获得列号,根据列号返回字母

需要导入, 这两个函数存在于openpyxl.utils

from openpyxl.utils import get_column_letter, column_index_from_string

根据列的数字返回字母

print(get_column_letter(2)) # B

根据字母返回列的数字

print(column_index_from_string('D')) # 4

Python使用openpyxl往excel文件中写入数据

参考链接:/276815076/p/8028127.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。