赞
踩
Python版本:3.6.5
IDE集成开发环境:pycharm
Python库选择:openpyxl
openpyxl操作的excel文件以xlsx结尾。
python --version
pip --version
pip install openpyxl -i https://pypi.tuna.tsinghua.edu.cn/simple/
openpyxl
创建,并保存一个 excel
文件from openpyxl import Workbook
wb = Workbook()
ws = wb.active
print(ws.title)
wb.save(r"C:\Users\Dell\Desktop\PDF\test.xlsx")
from openpyxl import Workbook, load_workbook
wb = load_workbook(r"C:\Users\Dell\Desktop\PDF\test.xlsx")
ws = wb.active
print(ws.title)
ws1 = wb.active # 查看当前工作表名 print(ws1.title) # 查看所有的工作表名 # print(wb.get_sheet_names()) # 查看所有的工作表名 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.get_sheet_names()) # 查看所有的工作表名 print(wb.sheetnames) ws2 = wb.create_sheet('Sheet2', 1) ws3 = wb.create_sheet('Sheet3', 2) # move_sheet移动工作表 # 参数offset代表偏移值,-1向前移动一个位置,1代表向后移动一个位置,以此类推。 wb.move_sheet(ws3, -1); # del wb['Sheet3'] print(wb.sheetnames)
Sheet
['Sheet']
['Sheet', 'Sheet3', 'Sheet2']
del wb['Sheet3']
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws['a6'] = '池田依来沙'
wb.save("test.xlsx")
from openpyxl import Workbook wb = Workbook() ws = wb.active # ws['a6'] = '池田依来沙' # cell方法的入参 # 譬如6就是row,代表第几行 # 譬如1就是column,代表第几列 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 # ws['a6'] = '池田依来沙' # cell方法的入参 # 譬如6就是row,代表第几行 # 譬如1就是column,代表第几列 cell = ws.cell(6, 1, "Malena") cell.value = 'morgan' print(cell.value) # coordinate 代表单元格的坐标,譬如 A6 print(cell.coordinate) # row,代表第几行 print(cell.row) # column,代表第几列 print(cell.column) # col_idx,代表第几列 print(cell.col_idx) # 第几列,用字母表示,譬如第一列为A 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 # 打印出A列到C列 print(ws["a:c"]) # 打印出第1行到第5行 print(ws["1:5"]) # 打印出a1到c4 print(ws["a1:c4"]) # 打印出第1行 print(ws["1"]) # 打印出字母C列表 print(ws["c"])
from openpyxl import Workbook wb = Workbook() ws = wb.active # ws['a6'] = '池田依来沙' # cell方法的入参 # 譬如6就是row,代表第几行 # 譬如1就是column,代表第几列 # cell = ws.cell(6, 1, "Malena") # # cell.value = 'morgan' # print(cell.value) # # coordinate 代表单元格的坐标,譬如 A6 # print(cell.coordinate) # # row,代表第几行 # print(cell.row) # # column,代表第几列 # print(cell.column) # # col_idx,代表第几列 # print(cell.col_idx) # # 第几列,用字母表示,譬如第一列为A # print(cell.column_letter) 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)
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 # 合并单元格 merge_cells 方法 ws.merge_cells("b2:d4") # 取消合并 unmerge_cells 方法 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")
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]) # 价格1 价格2 求和 平均值 # 95 27 # 48 31 # 11 23 # 求和 ws["c2"] = "=SUM(A2,B2)" # 平均值 ws["d2"] = "=AVERAGE(A2,B2)" # 翻译 Translator 方法 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") # 价格1 价格2 求和 平均值 # 95 27 122 61 # 48 31 79 39.5 # 11 23 34 17 # 循环遍历 for cell in ws["c3:c4"]: print(cell) # 打印得到一个元组,例如:(<Cell 'Sheet'.C3>,) cell[0].value = Translator(formula="=SUM(A2,B2)", origin="c2").translate_formula(cell[0].coordinate) wb.save("test.xlsx")
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")
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" # 过滤方法 add_filter_column 入参:第几列(从2开始),过滤条件 ws.auto_filter.add_filter_column(0, ["mila", "malena"]) # 排序方法 入参: 范围,排序方式(False升序,True倒序) ws.auto_filter.add_sort_condition("c2:d6", True) wb.save('test.xlsx')
注意,add_filter_column和add_sort_condition方法并不会直接执行排序,需要打开excel文件后,在筛选和排序上点击确认才能真正的执行。
pip install pandas
import pandas as pd
df = pd.read_excel('test.xlsx', sheet_name="Sheet")
# ascending True代表升序 ,False代表倒序
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()
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 = '销量' # Y轴 c1.x_axis.title = '月份' # X轴 # 选择数据范围 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" # triangle为三角形标记, 可选circle、dash、diamond、dot、picture、plus、square、star、triangle、x、auto s0.marker.graphicalProperties.solidFill = "FF0000" # 填充颜色 s0.marker.graphicalProperties.line.solidFill = "0000FF" # 边框颜色 # s0.graphicalProperties.line.noFill = True # 改为True则隐藏线条,但显示标记形状 s1 = c1.series[1] s1.graphicalProperties.line.solidFill = "00AAAA" s1.graphicalProperties.line.dashStyle = "sysDot" # 线条点状样式 s1.graphicalProperties.line.width = 80000 # 线条大小,最大20116800EMUs s2 = c1.series[2] # 采用默认设置 s2.smooth = True # 线条平滑 ws.add_chart(c1, "A8") # 图表位置 wb.save("line.xlsx")
读写大文件,使用只读只写模式
只读取数值用于其他数据分析,不改变和保存。
from openpyxl import load_workbook
# 加载Excel文件时使用read_only指定只读模式
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')
如果你对Python感兴趣,想要学习python,这里给大家分享一份Python全套学习资料,都是我自己学习时整理的,希望可以帮到你,一起加油!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。