1、基本概念
在openpyxl中,主要有以下几个概念:Workbooks、Sheets、Cells,Workbook表示一个excel工作表,Sheet表示工作表中的每个表页,Cell表示一个单元格。
(1)创建一个表单,并往里面填入数据
from openpyxl import Workbook
import datetime
wb = Workbook()
ws = wb.active
ws['A1']=42
ws.append([1,2,3])
ws['A2'] = datetime.datetime.now()
wb.save('sample.xlsx')
wb = Workbook():创建一个工作表
ws = wb.active:找到活动的sheet页
ws['A1']=42:往A1单元格中写入数据
sheet.title = "New Shit":给sheet页重命名
wb.save('sample.xlsx'):保存
wb.create_sheet("Mysheet"):创建新的sheet页
ws.sheet_properties.tabColor = "1072BA":修改sheet标签的颜色
d = ws.cell(row=4, column=2, value=10):使用单元格行列对单元格进行访问
cell_range = ws['A1':'C2']:访问多个单元格
遍历标签页
for sheet in wb:
... print(sheet.title)
创建sheet的副本
source = wb.active
target = wb.copy_worksheet(source)
返回行值
for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
... for cell in row:
... print(cell)
返回列值
for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
... for cell in col:
... print(cell)
得到结果:
(2)读取excel
from openpyxl import load_workbook
wb = load_workbook("test10.xlsx")
print(wb.sheetnames)
# 输出:['Sheet1', 'Sheet2', 'Sheet3']
sheet = wb.get_sheet_by_name('Sheet3')