假设一个名叫“模板”的excel表格里有四个sheet,名字分别是[‘平台’, ‘制冷’, ‘洗衣机’, ‘空调’]
1、读取
from openpyxl import load_workbook
namelists=['平台', '制冷', '洗衣机', '空调']
wb = load_workbook("模板.xlsx")
显示有多少张sheet
print(wb.sheetnames)
['平台', '制冷', '洗衣机', '空调']
读取sheet的单元格
ws=wb['平台']
ws.cell(row=1, column=3).value
'小微'
读取多个sheet的单元格
for i in wb.sheetnames:
ws=wb[i]
ws.cell(row=1, column=3).value
print(ws.max_row)
print(ws.max_column)
16
19
2、写入数据到sheet的单元格,写完一定要保存,使用文件后要关闭
ws=wb['平台']
ws.cell(row=5, column=4).value="hello"
for i in range(5,10):
for j in range(5,10):
ws.cell(row=i, column=j).value=1
wb.save("1.xlsx")
wb.close()
写入多个sheet的单元格
wb = load_workbook("模板.xlsx")
for i in wb.sheetnames:
ws=wb[i]
ws.cell(row=1, column=3).value=1
wb.save("1.xlsx")
wb.close()