openpyxl是一个第三方库,可以处理xlsx格式的Excel文件。
安装:
pip install openpyxl
对如下excel进行读取操作,如图:
from openpyxl import load_workbook wb = load_workbook("123.xlsx") print(wb.get_sheet_names()) #>>>[Sheet111,Sheet222,Sheet333] a_sheet = wb.get_sheet_by_name("Sheet111") print(a_sheet.title) #>>>Sheet111 a1 = a_sheet['A1'] print(f'({a1.column}, {a1.row}) is {a1.value}') #>>>3 a1_too =a_sheet.cell(row = 4, column = 2) print(a1_too.value) #>>>fvf # 获得最大列和最大行 print(a_sheet.max_row) #>>>6 print(a_sheet.max_column) #>>>4 for row in a_sheet.rows: for cell in row: print(cell.value,end = '\t') print('\n') ''' >>> 3 3 None None 4 None None None 5 None fv fv 6 fvf None None 7 None None None 909 None None None ''' #获取某一行或者某一列的数据 for cell in list(a_sheet.rows)[3]: print(cell.value,end = "\t") #>>>6 fvf None None #获取任意区间的单元格 for i in range(2, 4): for j in range(1, 3): print(a_sheet.cell(row=i, column=j).value,end = "\t") #>>>4 None 5 None
对文件的写入操作:
from openpyxl import Workbook wb = Workbook() ws = wb.active #创建一张新的表 ws1 = wb.create_sheet("botoo") #写入数据 ws1["a1"]=10086 #或者 ws1["a2"].value= 1111111 #为B列创建数据 1~19 for i in range(1,20): ws1["B%d" %i] .value= i #为20行创建数据 1~10 for i in range(1,20): ws1.cell(column = i, row = 20).value = i wb.save("这是python写入3.xlsx")
效果如下:
*当需要对已有文件进行更改的时候,需要使用:
>>> from openpyxl import load_workbook
>>>wb2 = load_workbook('test.xlsx')
>>> print wb2.get_sheet_names()
['Sheet2', 'New Title', 'Sheet1']
否则文件内容会被覆盖。
参考文章:
http://openpyxl.readthedocs.io/en/stable/
https://blog.csdn.net/hunter_wyh/article/details/78498323
http://www.pythontab删去汉字.com/html/2018/pythonhexinbiancheng_0503/1286.html
(不知道为什么Python中文开发社区的链接放不上去)
来源:https://www.cnblogs.com/botoo/p/9005387.html