openpyxl模块让python程序能够读取和修改Excel电子表格文件,生成需要的新点子表格。从许多的几万行级的电子表格中定位需要的数据或需要处理的数据,并进行精细化加工,替代低效率的脑残体力劳动,正是openpyx的可爱之处。
之前在”python进阶宝典10-Excel处理(https://blog.csdn.net/ebzxw/article/details/80261507)“中,已经详细的列明了openpyxl对excel的各类读写基本操作,以及设置字体、公式、行高、列宽、合并拆分单元格、生成冻结窗口、图表处理等各种操作的实现方法,并列出了code。
openpyxl通过charts进行图表处理,详细官方文档链接:http://openpyxl.readthedocs.io/en/stable/charts/bar.html
这里在就强大图表处理功能进行下补充。实在是太强大,各种图表都有如下。
以BarChart为例, 在BarChart中,图表类型可以通过众多参数设置。
值被绘制为水平条或垂直列:通过将类型设置为COL或BAR,即可在垂直和水平条形图之间切换;当使用堆叠图时,重叠需要设置为100。可以通过chartObj.y_axis.title='Test_y', chartObj.x_axis.title='Test_x' 设置坐标轴的属性;通过chartObj.type='col' (col为纵向,bar为横向),chartObj.title='Bar chart' 等来设置图表的属性等。
以下代码生成4种2D图表。
from openpyxl import Workbook
from openpyxl.chart import BarChart, Series, Reference
wb = Workbook(write_only=True)
ws = wb.create_sheet()
rows = [
('Number', 'Batch 1', 'Batch 2'),
(2, 10, 30),
(3, 40, 60),
(4, 50, 70),
(5, 20, 10),
(6, 10, 40),
(7, 50, 30),
]
for row in rows:
ws.append(row)
chart1 = BarChart()
chart1.type = "col"
chart1.style = 10
chart1.title = "Bar Chart"
chart1.y_axis.title = 'Test number'
chart1.x_axis.title = 'Sample length (mm)'
data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)
cats = Reference(ws, min_col=1, min_row=2, max_row=7)
chart1.add_data(data, titles_from_data=True)
chart1.set_categories(cats)
chart1.shape = 4
ws.add_chart(chart1, "A10")
from copy import deepcopy
chart2 = deepcopy(chart1)
chart2.style = 11
chart2.type = "bar"
chart2.title = "Horizontal Bar Chart"
ws.add_chart(chart2, "G10")
chart3 = deepcopy(chart1)
chart3.type = "col"
chart3.style = 12
chart3.grouping = "stacked"
chart3.overlap = 100
chart3.title = 'Stacked Chart'
ws.add_chart(chart3, "A27")
chart4 = deepcopy(chart1)
chart4.type = "bar"
chart4.style = 13
chart4.grouping = "percentStacked"
chart4.overlap = 100
chart4.title = 'Percent Stacked Chart'
ws.add_chart(chart4, "G27")
wb.save("bar.xlsx")
代码验证通过,效果如下:
以下代码生成3D图表。
from openpyxl import Workbook
from openpyxl.chart import (
Reference,
Series,
BarChart3D,
)
wb = Workbook()
ws = wb.active
rows = [
(None, 2013, 2014),
("Apples", 5, 4),
("Oranges", 6, 2),
("Pears", 8, 3)
]
for row in rows:
ws.append(row)
data = Reference(ws, min_col=2, min_row=1, max_col=3, max_row=4)
titles = Reference(ws, min_col=1, min_row=2, max_row=4)
chart = BarChart3D()
chart.title = "3D Bar Chart"
chart.add_data(data=data, titles_from_data=True)
chart.set_categories(titles)
ws.add_chart(chart, "E5")
wb.save("bar3d.xlsx")
代码验证通过,效果如下: