欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

Python使用openpyxl读写excel文件

发布时间:2025/3/20 python 41 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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文件中写入数据

参考链接:https://www.cnblogs.com/276815076/p/8028127.html

总结

以上是生活随笔为你收集整理的Python使用openpyxl读写excel文件的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。