先跑demo
from openpyxl import Workbook
wb = Workbook()
# grab the active worksheet
ws = wb.active
# Data can be assigned directly to cells
# ws['A1'] = 42
# Rows can also be appended
ws.append([1, 2, 3])
# Python types will automatically be converted
import datetime
ws['A2'] = datetime.datetime.now()
for i in ws.rows:
print(i)
# print(ws.rows)
# Save the file
# wb.save("sample.xlsx")
基本操作
import openpyxl
df=openpyxl.load_workbook("costDay.xlsx") #读取已有文件
ws=df.active #取得当前sheet
for i in ws.rows:
#取得每一行的cell对象。(<Cell 'Sheet'.A1>, <Cell 'Sheet'.B1>, <Cell 'Sheet'.C1>)
print(i)
#访问一个单元格(通过位置访问)
c = ws['A4']
#或者 row 是行,column是列,value是传递的值。如果只是读取已有的值,value可以不传.此处为:取sheet里第一行第一列的cell,setvalue为10.
d = ws.cell(row=1, column=1, value=10)
# 写操作
data=[1,2,3,4,5]
ws.append(data)
#保存,注意:调用的是book对象实行保存。
wb.save('sample.xlsx')
ps:详细教程还是看官网
https://openpyxl.readthedocs.io/en/stable/tutorial.html