from openpyxl import Workbook, load_workbook
wb = load_workbook(r"C:\Users\Dell\Desktop\PDF\test.xlsx")
ws = wb.active
print(ws.title)
3.操作工作表
ws1 = wb.active
print(ws1.title)
print(wb.sheetnames)
ws2 = wb.create_sheet('Sheet2', 1)
ws3 = wb.create_sheet('Sheet3', 2)
print(wb.sheetnames)
ws4 = wb['Sheet3']
print(ws4.title)
运行后,控制台打印如下结果
Sheet
['Sheet']
['Sheet', 'Sheet2', 'Sheet3']
Sheet3
from openpyxl import Workbook
wb = Workbook()
ws1 = wb.active
print(ws1.title)
print(wb.sheetnames)
ws2 = wb.create_sheet('Sheet2', 1)
ws3 = wb.create_sheet('Sheet3', 2)
wb.move_sheet(ws3, -1);
print(wb.sheetnames)
运行后,控制台打印如下结果,Sheet3移动到了Sheet2前面
Sheet
['Sheet']
['Sheet', 'Sheet3', 'Sheet2']
del wb['Sheet3']
4.访问单元格
写入单元格的值
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws['a6'] = '池田依来沙'
wb.save("test.xlsx")
修改单元格的值
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
cell = ws.cell(6, 1, "Malena")
cell.value = 'morgan'
print(cell.value)
wb.save("test.xlsx")
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
cell = ws.cell(6, 1, "Malena")
cell.value = 'morgan'
print(cell.value)
print(cell.coordinate)
print(cell.row)
print(cell.column)
print(cell.col_idx)
print(cell.column_letter)
wb.save("test.xlsx")
循环遍历,以及打印单元格
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
x = 1
for i in range(1, 11):
for j in range(1, 6):
ws.cell(i, j, x)
x += 1
print(ws["a:c"])
print(ws["1:5"])
print(ws["a1:c4"])
print(ws["1"])
print(ws["c"])
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
x = 1
for i in range(1, 11):
for j in range(1, 6):
ws.cell(i, j, x)
x += 1
for cells in ws["a1:c4"]:
for cell in cells:
print(cell)
print(cell.value)
5.操作单元格
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
x = 1
for i in range(1, 11):
for j in range(1, 11):
ws.cell(i, j, x)
x +=1
ws.merge_cells("b2:d4")
ws.unmerge_cells("b2:d4")
ws.insert_cols(2, 3)
ws.insert_rows(1, 2)
ws.delete_cols(6, 2)
ws.delete_rows(6, 3)
ws.move_range("c4:e5", 2, -2)
wb.save("test.xlsx")
6.使用公式
from openpyxl import Workbook
from openpyxl.formula.translate import Translator
from openpyxl.utils import FORMULAE
wb = Workbook()
ws = wb.active
print(len(FORMULAE))
print('SUM' in FORMULAE)
ws.append(["价格1", "价格2", "求和", "平均值"])
ws.append([95,27])
ws.append([48,31])
ws.append([11,23])
ws["c2"] = "=SUM(A2,B2)"
ws["d2"] = "=AVERAGE(A2,B2)"
ws["c3"] = Translator(formula="=SUM(A2,B2)", origin="c2").translate_formula("c3")
ws["c4"] = Translator(formula="=SUM(A2,B2)", origin="c2").translate_formula("c4")
ws["d3"] = Translator(formula="=AVERAGE(A2,B2)", origin="d2").translate_formula("d3")
ws["d4"] = Translator(formula="=AVERAGE(A2,B2)", origin="d2").translate_formula("d4")
for cell in ws["c3:c4"]:
print(cell)
cell[0].value = Translator(formula="=SUM(A2,B2)", origin="c2").translate_formula(cell[0].coordinate)
wb.save("test.xlsx")
7.设置样式
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment
wb = Workbook()
ws = wb.active
ws["a1"] = "池田依来沙"
f = Font(name="微软雅黑", size=42, color="F56C6C", bold=True, italic=True, strike=True, underline="double")
ws["a1"] .font = f
ws.row_dimensions[2].height = 100
ws.column_dimensions["B"].width = 50
a = Alignment(horizontal="left", vertical="top", text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0)
ws["a1"].alignment = a;
wb.save("test.xlsx")
8.过滤和排序
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
rows = [
['名称', '颜值', '身材', '价值'],
['mila', '80', '90', '99'],
['malena', '80', '90', '96'],
['morgan', '100', '90', '99'],
['sf', '80', '20', '97'],
['ac', '30', '90', '92'],
for row in rows:
ws.append(row)
ws.auto_filter.ref = "a1:d7"
ws.auto_filter.add_filter_column(0, ["mila", "malena"])
ws.auto_filter.add_sort_condition("c2:d6", True)
wb.save('test.xlsx')
注意,add_filter_column和add_sort_condition方法并不会直接执行排序,需要打开excel文件后,在筛选和排序上点击确认才能真正的执行。
通过安装第三方库,譬如pandas可以直接执行排序和筛选的操作
pip install pandas
pandas 的使用
import pandas as pd
df = pd.read_excel('test.xlsx', sheet_name="Sheet")
df_value = df.sort_values(by=["颜值","身材"], ascending=True)
writer = pd.ExcelWriter("test2.xlsx")
df_value.to_excel(writer,sheet_name="Sheet2", index=False)
writer.save()
9.插入图表
openpyxl图表官网地址
from openpyxl import Workbook
from openpyxl.chart import LineChart, Reference
wb = Workbook()
ws = wb.active
rows = [
['月份', '桃子', '西瓜', '龙眼'],
[1, 38, 28, 29],
[2, 52, 21, 35],
[3, 39, 20, 69],
[4, 51, 29, 41],
[5, 29, 39, 31],
[6, 30, 41, 39],
for row in rows:
ws.append(row)
c1 = LineChart()
c1.title = "折线图"
c1.style = 13
c1.y_axis.title = '销量'
c1.x_axis.title = '月份'
data = Reference(ws, min_col=2, min_row=1, max_col=4, max_row=7)
c1.add_data(data, titles_from_data=True)
s0 = c1.series[0]
s0.marker.symbol = "triangle"
s0.marker.graphicalProperties.solidFill = "FF0000"
s0.marker.graphicalProperties.line.solidFill = "0000FF"
s1 = c1.series[1]
s1.graphicalProperties.line.solidFill = "00AAAA"
s1.graphicalProperties.line.dashStyle = "sysDot"
s1.graphicalProperties.line.width = 80000
s2 = c1.series[2]
s2.smooth = True
ws.add_chart(c1, "A8")
wb.save("line.xlsx")
10.只读只写
读写大文件,使用只读只写模式
只读取数值用于其他数据分析,不改变和保存。
from openpyxl import load_workbook
wb = load_workbook(filename='large_file.xlsx', read_only=True)
ws = wb['big_data']
for row in ws.rows:
for cell in row:
print(cell.value)
wb.close()
可以在创建的时候指定为只写模式以便提高性能,不管文件有多大,都可以把内存保持在10M以下。
from openpyxl import Workbook
from openpyxl.cell import WriteOnlyCell
from openpyxl.comments import Comment
from openpyxl.styles import Font
wb = Workbook(write_only=True) # 创建工作簿时指定只写模式
ws = wb.create_sheet() # 需要通过create_sheet创建一个sheet
# 可以正常保存数据
for _ in range(100):
ws.append([i for i in range(200)]) # 只能通过append写
# 如果需要保留公式、注释等操作,可以使用WriteOnlyCell
cell = WriteOnlyCell(ws, value="冰冷的希望")
cell.font = Font(name='黑体', size=15)
cell.comment = Comment(text="这是注释", author="pan")
ws.append([cell])
wb.save('openpyxl/test.xlsx')
复制代码