1.获取和修改单个单元格
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
cell = ws["a6"]
cell2 = ws.cell(1, 2)
ws["a5"] = 666
ws['A3'] = datetime.datetime.now().strftime("%Y-%m-%d")
ws.append([1, 2, 3])
cell = ws["a6"]
cell.value = 777
print(cell, cell.value)
cell2 = ws.cell(6, 1)
print(cell2, cell2.value)
print(c.coordinate)
print(c.column_letter)
print(c.col_idx)
print(c.row)
1.如果使用cell(row, column, value)获取,第一个参数是行,第二个参数是列,下标都是从1开始,例如,ws[“a6”]等同于ws.cell(6, 1),但如果指定了第三个参数value,则修改了该单元格的值 2.只要访问了一个cell就会被创建,不管是否赋值
根据上面的方式,我们可以通过循环来准备一下数据
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
i = 1
for x in range(1, 11):
for y in range(1, 21):
ws.cell(row=x, column=y, value=i)
i += 1
wb.save("test.xlsx")
这样我们就得到了从1~200共200个(10行20列)单元格的数据
2.获取多个单元格
2.1 通过范围取值
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
i = 1
for x in range(1, 11):
for y in range(1, 21):
ws.cell(row=x, column=y, value=i)
i += 1
row_cells = ws[2]
print(row_cells)
col_cells = ws["b"]
print(col_cells)
row_range_cells = ws[2:5]
print(row_range_cells)
col_range_cells = ws["B:D"]
print(col_range_cells)
range_cells = ws["c3:f6"]
print(range_cells)
1.以上输出应该类似<Cell ‘Sheet’.A2>、 <Cell ‘Sheet’.B2>,为了好看,简化为A2、B2的形式 2.以上获取到的多个单元格,返回的是元组或元组套元组,可以通过遍历的方式访问或修改
2.2 通过iter_rows或iter_cols取值
iter_rows()与iter_cols()都可以指定最大最小的行列,下标从1开始 返回结果是生成器
...
cells = ws.iter_rows(min_row=1, max_row=3, min_col=2, max_col=5)
for cell in cells:
print(cell)
cells = ws.iter_cols(min_row=1, max_row=3, min_col=2, max_col=5)
for cell in cells:
print(cell)
iter_cols和iter_rows都可以指定参数values_only=True,这样只返回值而不是cell对象
也可以使用rows或columns属性遍历全部行或列,values属性取出所有值,它们都得到迭代器,但是注意只读模式下columns属性无效
for cell in ws.rows:
print(cell)
for cell in ws.columns:
print(cell)
for row in ws.values:
for value in row:
print(value)
3.操作单元格
3.1合并单元格
合并单元格,会保留最左上角的单元格的数据和样式,其他单元格会被清空,即使取消合并。即,合并之后只保留左上角第一个单元格的数据和样式
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
i = 1
for x in range(1, 11):
for y in range(1, 21):
ws.cell(row=x, column=y, value=i)
i += 1
print(ws["C2"].value)
ws.merge_cells("A1:F3")
ws.unmerge_cells("A1:F3")
print(ws["C2"].value)
wb.save("./test.xlsx")
3.2 删除或插入行列
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
i = 1
for x in range(1, 11):
for y in range(1, 21):
ws.cell(row=x, column=y, value=i)
i += 1
ws.insert_cols(5)
ws.insert_rows(2, 3)
ws.delete_cols(2, 3)
ws.delete_rows(5, -3)
wb.save("./test.xlsx")
3.3 移动单元格
可以使用move_range()合并指定范围的单元格,但是注意,如果移动到的位置原来有数据会被覆盖掉,移动之后公式会丢失,可以通过设置translate=True来更新,默认是False
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
i = 1
for x in range(1, 11):
for y in range(1, 21):
ws.cell(row=x, column=y, value=i)
i += 1
ws.move_range("B1:D3", rows=6, cols=-1, translate=False)
wb.save("./test.xlsx")
|