python操做Excel、openpyxl 之圖表,折線圖、餅圖、柱狀圖等

1、準備
  • 須要模塊:
    from openpyxl.workbook import Workbook
    from openpyxl.chart import Series,LineChart, Reference
1.1 建表,畫圖
  • openpyxl支持利用工做表中單元格的數據,建立條形圖、折線圖、散點圖等json

  • 步驟:app

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 獲取
    其餘的就是指定這個表中的行列數據了:起始行、起始列、終止行、終止列ide

  2. 經過傳入Reference對象,建立一個Series對象測試

  3. 建立一個Chart對象字體

  4. 可選擇的設置Chart對象的長(drawing.height)、寬(drawing.width)、座標位置(drawing.top、drawing.left)。ui

  5. 將Chart對象添加到Worksheet對象。excel

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 做者最近工做用的一個圖

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')
相關文章
相關標籤/搜索