python操作Excel、openpyxl 之图表,折线图、饼图、柱状图等

一、准备
  • 需要模块:
    from openpyxl.workbook import Workbook
    from openpyxl.chart import Series,LineChart, Reference
1.1 建表,画图
  • openpyxl支持利用工作表中单元格的数据,创建条形图、折线图、散点图等

  • 步骤:

wb = Workbook()
ws = wb.create_sheet("{0}蒸汽压力记录表".format("样品名称"), 0)  
  1. 从将表格中涉及的要画图的数据使用:Reference 创建一个对象
    比如:我选取 data = Reference(ws, min_col=5, min_row=4, max_col=10, max_row=4)
    参数含义:ws 一个活跃的sheet,数据来源。可以使用ws = wb.active 获取
    其他的就是指定这个表中的行列数据了:起始行、起始列、终止行、终止列

  2. 通过传入Reference对象,创建一个Series对象

  3. 创建一个Chart对象

  4. 可选择的设置Chart对象的长(drawing.height)、宽(drawing.width)、坐标位置(drawing.top、drawing.left)。

  5. 将Chart对象添加到Worksheet对象。

chart = LineChart()  #图表对象

data = Reference(ws, min_col=5, min_row=4, max_col=10, max_row=4) #涉及数据

seriesObj = Series(data, title='压力')  #创建series对象

chart.append(seriesObj)  #添加到chart中

ws.add_chart(chart, "A6") #将图表添加到 sheet中
1.2 其他方式画图
  • 一个饼图
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference, Series

wb = load_workbook('e:\\sample.xlsx')
ws1=wb.active

wb = Workbook()
ws = wb.active
for i in range(10):
    ws.append([i])

values = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
chart = BarChart()
chart.add_data(values)
ws.add_chart(chart, "E15")

# Save the file
wb.save("e:\\sample.xlsx")
3.1.2 作者最近工作用的一个图

python操作Excel、openpyxl 之图表,折线图、饼图、柱状图等_第1张图片

import uuid
import string
import json
import time
import os
import base64

from openpyxl.workbook import Workbook
from openpyxl.styles import Font, Alignment, Side, Border
from openpyxl.drawing import image
from openpyxl.chart import Series,LineChart, Reference

from Lib.Utils import Utils

class ExportReport:

    def __init__(self, start_time, water_temp, test_people,
                 sample_name, pressure_value, pressure_list,*args, **kwargs):
        """

        :param start_time: 实验开始时间
        :param water_temp: 水浴温度
        :param test_people: 试验人
        :param sample_name: 样品名称
        :param pressure_value: 最终压力
        :param args: 实验过程压力记录列表
        :param kwargs:
        """
        self.start_time = start_time
        self.water_temp = str(water_temp)+' ℃'
        self.test_people = test_people
        self.sample_name = sample_name
        self.pressure_value = pressure_value
        self.all_col = 5+len(pressure_list) #一共多少列
        self.pressure_record = pressure_list #第六列到最后一列的数据列表
        self.image_path = kwargs.get('imgPath', None)  #图片路径
        #所有的数据列
        self.data_list = [
            self.start_time, self.water_temp,
            self.test_people,self.sample_name,
            self.pressure_value
        ]
        self.data_list.extend(self.pressure_record)
        self.col_list = ["开始时间", "水浴温度", "测试人", "样品名称", "最终压力值"]

        # base64转化为图片
        # self.bs64 = bs64
        # self.img_path = Utils.change_base64_as_img(self.bs64)

        self.wb = Workbook()
        #self.wb.remove(self.wb["sheet"])

        self.ws = self.wb.create_sheet("{0}蒸汽压力记录表".format(self.sample_name), 0)
        #生成所含列总数的大写字母
        self.upper_string_list = string.ascii_uppercase[:self.all_col]
        # 水平对齐,居中对齐
        self.alignment_style = Alignment(horizontal='center', vertical='center')
        #定义border 边框样式
        left, right, top, bottom = [Side(style='thin', color='000000')]*4
        self.border_style = Border(left=left, right=right, top=top, bottom=bottom)
        #定义字体
        self.font_size = Font(size=9)
        for col in self.upper_string_list:
            self.ws.column_dimensions[col].width = 20

    #单元格样式字体调整
    def cell_set(self, cellObj, fontSzie=12, alignmentStyle=None):
        alignmentStyle = alignmentStyle if alignmentStyle else self.alignment_style
        cellObj.alignment = alignmentStyle
        cellObj.font = Font(size=fontSzie, bold=True)

    #创建表头第一行
    def create_row1(self):
        #把所有列合并
        self.ws.merge_cells(start_row=1, end_row=1, start_column=1, end_column=self.all_col)
        #写入值
        # self.ws.cell(row=1, column=1).value = value
        self.ws.cell(row=1, column=1).value = "{0}蒸汽压力记录表".format(self.sample_name)
        # self.ws['A1'].alignment = self.alignment_style
        # self.ws['A1'].font = Font(size=16, bold=True)
        self.cell_set(self.ws['A1'], 16)
        self.create_row2_3()

    def create_row2_3(self):
        #把前五列,二三行单元格合并,并写入值
        for col in range(1, len(self.col_list)+1):
            self.ws.merge_cells(start_row=2, end_row=3, start_column=col, end_column=col)
            col_str = self.upper_string_list[col-1]+"2"
            self.ws[col_str] = self.col_list[col-1]
            # self.ws[col_str].alignment = self.alignment_style
            # self.ws[col_str].font = Font(size=12, bold=True)
            self.cell_set(self.ws[col_str])

        #把第二行第六列开始到最后列合并
        self.ws.merge_cells(start_row=2, end_row=2, start_column=len(self.col_list)+1, end_column=self.all_col)
        col_str = self.upper_string_list[len(self.col_list)]+"2"
        self.ws[col_str] = "实验过程压力记录"
        # self.ws[col_str].alignment = self.alignment_style
        # self.ws[col_str].font = Font(size=12, bold=True)
        self.cell_set(self.ws[col_str])

        #第三行第六列开始到最后列写入值
        for index, col_ltr in enumerate(self.upper_string_list[len(self.col_list):]):
            col_str = col_ltr+'3'
            self.ws[col_str] = "第{0}次压力记录".format(index+1)
            # self.ws[col_str].alignment = self.alignment_style
            # self.ws[col_str].font = Font(size=12, bold=True)
            self.cell_set(self.ws[col_str])

    def add_data(self):
        #第四行开始写入数据,所有数据居中对齐,水平居中
        for index, col in enumerate(self.upper_string_list):
            col_str = col+"4"
            self.ws[col_str] = self.data_list[index]
            # self.ws[col_str].alignment = self.alignment_style
            # self.ws[col_str].font = Font(size=12, bold=True)
            self.cell_set(self.ws[col_str])

    #画折线图
    def draw_line_chart(self):
        data_col = self.ws["{0}:{1}".format(self.upper_string_list[len(self.col_list)]+"3",self.upper_string_list[-1]+"3" )]
        self.chart = LineChart()
        self.chart.width = 21.2
        self.chart.height = 8
        self.chart.style = 2 ##线条的style,Max value is 48   2 10
        self.chart.title = "压力记录图"
        self.chart.y_axis.title = "压力值"
        self.chart.x_axis.title = "压力测量次数"
        #从活动表中关联压力记录次数数据, 第六行到第10行
        data = Reference(
            self.ws,
            min_col=len(self.col_list)+1,
            min_row=4,
            max_col=self.all_col,
            max_row=4
        )
        #将数据添加到系列中
        seriesObj = Series(data, title='压力')
        format_str = "第{0}次记录:/n压力:{1}".format(seriesObj.xVal,seriesObj.yVal)
        # seriesObj.labels
        self.chart.append(seriesObj)
        # self.chart.add_data(data, from_rows=False)
        # style = self.chart.series[0]
        # style.smooth = True
        self.ws.add_chart(self.chart, "A6")

    def create(self,value=None):
        if value:
            self.ws.cell(row=1, column=1).value = value
        self.create_row1()
        self.add_data()
        self.draw_line_chart()

    def save(self, filename):
        try:
            self.wb.save(filename)
        except:
            self.wb.save(filename[:-5] + str('_' + Utils.getFileName()) + filename[-5:])

        # 关闭excel
        self.close()

    def close(self):
        self.wb.close()

if __name__ == '__main__':
    er = ExportReport(1, 2, 3, 4, 5, [17, 15, 19, 13,24])
    er.create()
    er.wb.save('17表.xlsx')

转载于:https://www.cnblogs.com/shiqi17/p/10752558.html

你可能感兴趣的:(python,json)