def create_pie_chart(sheet, numOfStocks, sectors): dictSector = Counter(sectors) pie = PieChart() labels = Reference(sheet, min_col=1, min_row=2, max_row=numOfStocks + 1) data = Reference(sheet, min_col=5, min_row=1, max_row=numOfStocks + 1) pie.add_data(data, titles_from_data=True) pie.set_categories(labels) pie.title = "Percentage of Shares in Portfolio" pie.height = 12 pie.width = 20 sheet.add_chart(pie, "K1") pie2 = PieChart() labels = Reference(sheet, min_col=7, min_row=27, max_row=26 + len(dictSector)) data = Reference(sheet, min_col=8, min_row=26, max_row=26 + len(dictSector)) pie2.add_data(data, titles_from_data=True) pie2.set_categories(labels) pie2.title = "Percentage of Sectors in Portfolio" pie2.height = 12 pie2.width = 20 sheet.add_chart(pie2, "K26")
def make_pie(sheet, left_col, top_row, bot_row, title, print_cell, height, width): left_col = int(left_col) right_col = left_col + 1 top_row = int(top_row) bot_row = int(bot_row) title = str(title) print_cell = str(print_cell) height = float(height) width = float(width) pie = PieChart() labels = Reference(sheet, min_col=left_col, max_col=left_col, min_row=top_row + 1, max_row=bot_row) data = Reference(sheet, min_col=right_col, max_col=right_col, min_row=top_row, max_row=bot_row) pie.add_data(data, titles_from_data=True) pie.set_categories(labels) pie.title = title pie.height = height pie.width = width sheet.add_chart(pie, print_cell) return None
def chartBreakdown(): '''Makes pie chart and bar chart for summary tab''' pie = PieChart() z = len(categories) data = Reference(Sum, min_col=9, min_row=2, max_row= z-1) labels = Reference(Sum, min_col=8, min_row=2, max_row= z-1) pie.add_data(data) pie.set_categories(labels) pie.title = 'Breakdown of Expenses' pie.width = 15.0 pie.height = 12.0 pie.legend.layout = Layout(manualLayout=ManualLayout(x=0.25, y=0.25, h=0.99, w=0.25)) Sum.add_chart(pie, 'A1') pie.dataLabels = DataLabelList() pie.dataLabels.showPercent = True bar = BarChart() barData1 = Reference(Sum, min_col=mNum+9, min_row=1, max_row=z-1) barData2 = Reference(Sum, min_col=mNum+12, min_row=1, max_row=z-1) bar.add_data(barData1, titles_from_data=True) bar.add_data(barData2, titles_from_data=True) bar.set_categories(labels) bar.title = 'Goal Comparison' bar.width = 2.0*z bar.height = 12.0 bar.legend.layout = Layout(manualLayout=ManualLayout(x=0.25, y=0.25, h=1.99, w=0.25)) Sum.add_chart(bar, 'A28')
def _draw_pie_charts(self): """ 画两个饼图 :return: None """ ws = self._wb['analysis'] # 设置单元格值,饼图引用 ws['G3'] = '失败' ws['G4'] = '通过' ws['H3'] = self._api_failure ws['H4'] = self._api_num - self._api_failure ws['N3'] = '失败' ws['N4'] = '通过' ws['O3'] = self._case_failure ws['O4'] = self._case_num - self._case_failure # 画接口饼图 pie = PieChart() labels = Reference(ws, min_col=7, min_row=3, max_row=4) data = Reference(ws, min_col=8, min_row=2, max_row=4) pie.add_data(data, titles_from_data=True) pie.set_categories(labels) pie.title = "接口执行情况" slice_ = DataPoint(idx=0, explosion=10) pie.series[0].data_points = [slice_] ws.add_chart(pie, "F1") pie.height = 9.5 pie.width = 13 self._log.info('已生成接口执行情况饼图.') # 画用例饼图 pie2 = PieChart() labels2 = Reference(ws, min_col=14, min_row=3, max_row=4) data2 = Reference(ws, min_col=15, min_row=2, max_row=4) pie2.add_data(data2, titles_from_data=True) pie2.set_categories(labels2) pie2.title = "用例执行情况" slice2_ = DataPoint(idx=0, explosion=10) pie2.series[0].data_points = [slice2_] ws.add_chart(pie2, "M1") pie2.height = 9.5 pie2.width = 13 self._log.info('已生成用例执行情况饼图.')
def B(): sheetB = wb.create_sheet('주요국가별 출원동향', 1) B그래프data = Data.주요국출원동향() for r in dataframe_to_rows(B그래프data, index=False, header=True): sheetB.append(r) sheetB.insert_cols(2) for row, cellobj in enumerate(list(sheetB.columns)[1]): n = '=right(A%d,2)' % (row + 1) cellobj.value = n sheetB['B22'] = '합계' sheetB['C22'] = '=SUM(C2:C21)' sheetB['D22'] = '=SUM(D2:D21)' sheetB['E22'] = '=SUM(E2:E21)' sheetB['F22'] = '=SUM(F2:F21)' chartB1 = LineChart() dataB1 = Reference(sheetB, min_col=3, min_row=1, max_row=21, max_col=6) catsB1 = Reference(sheetB, min_col=2, min_row=2, max_row=21) chartB1.add_data(dataB1, titles_from_data=True) chartB1.set_categories(catsB1) chartB1.y_axis.majorGridlines = None chartB1.width = 15 chartB1.height = 10 chartB1.legend.position = 't' chartB1.graphical_properties = GraphicalProperties(ln=LineProperties( noFill=True)) sheetB.add_chart(chartB1, 'H2') chartB2 = PieChart() dataB2 = Reference(sheetB, min_col=3, min_row=22, max_col=6) labelsB2 = Reference(sheetB, min_col=3, min_row=1, max_col=6) chartB2.add_data(dataB2, from_rows=22, titles_from_data=False) chartB2.set_categories(labelsB2) chartB2.width = 5 chartB2.height = 5 chartB2.legend = None chartB2.graphical_properties = GraphicalProperties( ln=LineProperties(noFill=True, solidFill=None, gradFill=None)) chartB2.dLbls = DataLabelList() chartB2.dLbls.showPercent = True sheetB.add_chart(chartB2, 'M1')
def monthChartBreakdown(): '''Makes pie chart for each month''' curMonth = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] for i in range(1, mNum+1): pie = PieChart() length_m = len(categories) monthData = Reference(Sum, min_col = i+9, min_row = 2, max_row = length_m-1) labels = Reference(Sum, min_col=8, min_row=2, max_row = length_m-1) pie.add_data(monthData) pie.set_categories(labels) pie.title = curMonth[i]+ ' Expenses by Category' pie.width = 18.0 pie.height = 12.0 pie.legend.layout = Layout(manualLayout=ManualLayout(x=0.25, y=0.25, h=0.99, w=0.25)) wb.get_sheet_by_name(TM[i]).add_chart(pie, 'G3')
def chart_pie(self, ws, destination_cell_coordinate, label_min_row, label_max_row, label_min_col, label_max_col, data_min_row, data_max_row, data_min_col, data_max_col, title='',from_rows=False, chart_height = default_chart_height, chart_width = default_chart_width, is_3d = False, add_chart = True , **kw ): if is_3d: chart = PieChart3D() else: chart = PieChart() # print("@@@@@@@@@@@@@@@ title = {title} @@@@@@@@@@@@@@@@@@".format(title=title)) # print("default_height={} | width:{} ||| new: {} | {}".format(chart.height, chart.width, chart_height, chart_width)) chart.height = chart_height # default is 7.5 chart.width = chart_width # default is 15 # print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") # print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") # print("@@@@@@@@@@@@@@@ title = {title} @@@@@@@@@@@@@@@@@@".format(title=title)) # print("labels = min_col={label_min_col}, max_col={label_max_col}, min_row={label_min_row}, max_row={label_max_row}".format(label_min_col=label_min_col,label_max_col=label_max_col,label_min_row=label_min_row,label_max_row=label_max_row,)) # print("data = min_col={data_min_col}, max_col={data_max_col}, min_row={data_min_row}, max_row={data_max_row}".format(data_min_col=data_min_col,data_max_col=data_max_col,data_min_row=data_min_row,data_max_row=data_max_row,)) # print("from_rows: ", from_rows) # print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") # print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") labels = Reference(ws, min_row=label_min_row, max_row=label_max_row, min_col=label_min_col, max_col=label_max_col,) data = Reference(ws, min_row=data_min_row, max_row=data_max_row, min_col=data_min_col, max_col=data_max_col,) chart.add_data(data, titles_from_data=False, from_rows=from_rows) chart.set_categories(labels) chart.title = title if add_chart: ws.add_chart(chart, destination_cell_coordinate) return chart
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active # Row height ws.row_dimensions[1].height = 102 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 42 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('L')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Constantia', size=15, bold=True) title_font = Font(name='宋体', size=15, bold=True) data_font = Font(name='Franklin Gothic Book', size=11) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000')) b_border = Border(bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_r_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") # img = Image("myems.png") img.width = img.width * 1.06 img.height = img.height * 1.06 ws.add_image(img, 'B1') # Title ws.row_dimensions[3].height = 60 ws['B3'].font = name_font ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'].font = name_font ws['C3'] = name ws['D3'].font = name_font ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'].font = name_font ws['E3'] = period_type ws['F3'].font = name_font ws['F3'].alignment = b_r_alignment ws['F3'] = 'Date:' ws['G3'].border = b_border ws['G3'].alignment = b_c_alignment ws['G3'].font = name_font ws['G3'] = reporting_start_datetime_local[: 10] + "__" + reporting_end_datetime_local[: 10] ws.merge_cells("G3:H3") if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename ################################################# # First: 能耗分析 # 6: title # 7: table title # 8~10 table_data # Total: 5 rows # if has not energy data: set low height for rows ################################################# reporting_period_data = report['reporting_period'] has_energy_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_energy_data_flag = False if has_energy_data_flag: ws['B6'].font = title_font ws['B6'] = name + ' 能耗分析' category = reporting_period_data['names'] ca_len = len(category) ws.row_dimensions[7].height = 60 ws['B7'].fill = table_fill ws['B7'].border = f_border ws['B8'].font = title_font ws['B8'].alignment = c_c_alignment ws['B8'] = '能耗' ws['B8'].border = f_border ws['B9'].font = title_font ws['B9'].alignment = c_c_alignment ws['B9'] = '单位面积能耗' ws['B9'].border = f_border ws['B10'].font = title_font ws['B10'].alignment = c_c_alignment ws['B10'] = '环比' ws['B10'].border = f_border col = '' for i in range(0, ca_len): col = chr(ord('C') + i) row = '7' cell = col + row ws[col + '7'].fill = table_fill ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = round(reporting_period_data['subtotals'][i], 2) ws[col + '8'].border = f_border ws[col + '9'].font = name_font ws[col + '9'].alignment = c_c_alignment ws[col + '9'] = round( reporting_period_data['subtotals_per_unit_area'][i], 2) ws[col + '9'].border = f_border ws[col + '10'].font = name_font ws[col + '10'].alignment = c_c_alignment ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \ if reporting_period_data['increment_rates'][i] is not None else "-" ws[col + '10'].border = f_border # TCE TCO2E end_col = col # TCE tce_col = chr(ord(end_col) + 1) ws[tce_col + '7'].fill = table_fill ws[tce_col + '7'].font = name_font ws[tce_col + '7'].alignment = c_c_alignment ws[tce_col + '7'] = "吨标准煤 (TCE)" ws[tce_col + '7'].border = f_border ws[tce_col + '8'].font = name_font ws[tce_col + '8'].alignment = c_c_alignment ws[tce_col + '8'] = round( reporting_period_data['total_in_kgce'] / 1000, 2) ws[tce_col + '8'].border = f_border ws[tce_col + '9'].font = name_font ws[tce_col + '9'].alignment = c_c_alignment ws[tce_col + '9'] = round( reporting_period_data['total_in_kgce_per_unit_area'] / 1000, 2) ws[tce_col + '9'].border = f_border ws[tce_col + '10'].font = name_font ws[tce_col + '10'].alignment = c_c_alignment ws[tce_col + '10'] = str(round(reporting_period_data['increment_rate_in_kgce'] * 100, 2)) + "%" \ if reporting_period_data['increment_rate_in_kgce'] is not None else "-" ws[tce_col + '10'].border = f_border # TCO2E tco2e_col = chr(ord(end_col) + 2) ws[tco2e_col + '7'].fill = table_fill ws[tco2e_col + '7'].font = name_font ws[tco2e_col + '7'].alignment = c_c_alignment ws[tco2e_col + '7'] = "吨二氧化碳排放 (TCO2E)" ws[tco2e_col + '7'].border = f_border ws[tco2e_col + '8'].font = name_font ws[tco2e_col + '8'].alignment = c_c_alignment ws[tco2e_col + '8'] = round( reporting_period_data['total_in_kgco2e'] / 1000, 2) ws[tco2e_col + '8'].border = f_border ws[tco2e_col + '9'].font = name_font ws[tco2e_col + '9'].alignment = c_c_alignment ws[tco2e_col + '9'] = round( reporting_period_data['total_in_kgco2e_per_unit_area'] / 1000, 2) ws[tco2e_col + '9'].border = f_border ws[tco2e_col + '10'].font = name_font ws[tco2e_col + '10'].alignment = c_c_alignment ws[tco2e_col + '10'] = str(round(reporting_period_data['increment_rate_in_kgco2e'] * 100, 2)) + "%" \ if reporting_period_data['increment_rate_in_kgco2e'] is not None else "-" ws[tco2e_col + '10'].border = f_border else: for i in range(6, 10 + 1): ws.row_dimensions[i].height = 0.1 ################################################# # Second: 分时电耗 # 12: title # 13: table title # 14~17 table_data # Total: 6 rows ################################################ has_ele_peak_flag = True if "toppeaks" not in reporting_period_data.keys() or \ reporting_period_data['toppeaks'] is None or \ len(reporting_period_data['toppeaks']) == 0: has_ele_peak_flag = False if has_ele_peak_flag: ws['B12'].font = title_font ws['B12'] = name + ' 分时电耗' ws.row_dimensions[13].height = 60 ws['B13'].fill = table_fill ws['B13'].font = name_font ws['B13'].alignment = c_c_alignment ws['B13'].border = f_border ws['C13'].fill = table_fill ws['C13'].font = name_font ws['C13'].alignment = c_c_alignment ws['C13'].border = f_border ws['C13'] = '分时电耗' ws['B14'].font = title_font ws['B14'].alignment = c_c_alignment ws['B14'] = '尖' ws['B14'].border = f_border ws['C14'].font = title_font ws['C14'].alignment = c_c_alignment ws['C14'].border = f_border ws['C14'] = round(reporting_period_data['toppeaks'][0], 2) ws['B15'].font = title_font ws['B15'].alignment = c_c_alignment ws['B15'] = '峰' ws['B15'].border = f_border ws['C15'].font = title_font ws['C15'].alignment = c_c_alignment ws['C15'].border = f_border ws['C15'] = round(reporting_period_data['onpeaks'][0], 2) ws['B16'].font = title_font ws['B16'].alignment = c_c_alignment ws['B16'] = '平' ws['B16'].border = f_border ws['C16'].font = title_font ws['C16'].alignment = c_c_alignment ws['C16'].border = f_border ws['C16'] = round(reporting_period_data['midpeaks'][0], 2) ws['B17'].font = title_font ws['B17'].alignment = c_c_alignment ws['B17'] = '谷' ws['B17'].border = f_border ws['C17'].font = title_font ws['C17'].alignment = c_c_alignment ws['C17'].border = f_border ws['C17'] = round(reporting_period_data['offpeaks'][0], 2) pie = PieChart() pie.title = name + ' 分时电耗' labels = Reference(ws, min_col=2, min_row=14, max_row=17) pie_data = Reference(ws, min_col=3, min_row=13, max_row=17) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 7.25 # cm 1.05*5 1.05cm = 30 pt pie.width = 9 # pie.title = "Pies sold by category" s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False # 标签显示 s1.dLbls.showVal = True # 数量显示 s1.dLbls.showPercent = True # 百分比显示 # s1 = CharacterProperties(sz=1800) # 图表中字体大小 *100 ws.add_chart(pie, "D13") else: for i in range(12, 18 + 1): ws.row_dimensions[i].height = 0.1 ################################################ # Fourth: 能耗详情 # current_row_number: title # current_row_number+1 ~ current_row_number+1+ca_len*6-1: line # current_row_number+1+ca_len*6: table title # current_row_number+1+ca_len*6~: table_data ################################################ current_row_number = 19 reporting_period_data = report['reporting_period'] times = reporting_period_data['timestamps'] has_detail_data_flag = True ca_len = len(report['reporting_period']['names']) parameters_names_len = len(report['parameters']['names']) parameters_parameters_datas_len = 0 for i in range(0, parameters_names_len): if len(report['parameters']['timestamps'][i]) == 0: continue parameters_parameters_datas_len += 1 table_row = current_row_number + (ca_len + parameters_parameters_datas_len) * 6 + 2 chart_start_row_number = current_row_number + 1 if "timestamps" not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0: has_detail_data_flag = False if has_detail_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 详细数据' ws.row_dimensions[table_row].height = 60 ws['B' + str(table_row)].fill = table_fill ws['B' + str(table_row)].font = title_font ws['B' + str(table_row)].border = f_border ws['B' + str(table_row)].alignment = c_c_alignment ws['B' + str(table_row)] = '日期时间' time = times[0] has_data = False max_row = 0 if len(time) > 0: has_data = True max_row = table_row + len(time) print("max_row", max_row) if has_data: for i in range(0, len(time)): col = 'B' row = str(table_row + 1 + i) # col = chr(ord('B') + i) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = time[i] ws[col + row].border = f_border for i in range(0, ca_len): # 38 title col = chr(ord('C') + i) ws[col + str(table_row)].fill = table_fill ws[col + str(table_row)].font = title_font ws[col + str(table_row)].alignment = c_c_alignment ws[col + str(table_row)] = reporting_period_data['names'][i] + \ " (" + reporting_period_data['units'][i] + ")" ws[col + str(table_row)].border = f_border # 39 data time = times[i] time_len = len(time) for j in range(0, time_len): row = str(table_row + 1 + j) # col = chr(ord('B') + i) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round( reporting_period_data['values'][i][j], 2) ws[col + row].border = f_border current_row_number = table_row + 1 + len(times[0]) ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '小计' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) # line # 39~: line line = LineChart() line.title = '报告期消耗 - ' + ws.cell(column=3 + i, row=table_row).value labels = Reference(ws, min_col=2, min_row=table_row + 1, max_row=max_row) line_data = Reference(ws, min_col=3 + i, min_row=table_row, max_row=max_row) # openpyxl bug line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 # cm 1.05*5 1.05cm = 30 pt line.width = 24 # pie.title = "Pies sold by category" line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' # line.dLbls.showCatName = True # label show line.dLbls.showVal = True # val show line.dLbls.showPercent = True # percent show # s1 = CharacterProperties(sz=1800) # font size *100 chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number + 6 * i) ws.add_chart(line, chart_cell) ########################################## has_parameters_names_and_timestamps_and_values_data = True ca_len = len(report['reporting_period']['names']) current_sheet_parameters_row_number = chart_start_row_number + ca_len * 6 if 'parameters' not in report.keys() or \ report['parameters'] is None or \ 'names' not in report['parameters'].keys() or \ report['parameters']['names'] is None or \ len(report['parameters']['names']) == 0 or \ 'timestamps' not in report['parameters'].keys() or \ report['parameters']['timestamps'] is None or \ len(report['parameters']['timestamps']) == 0 or \ 'values' not in report['parameters'].keys() or \ report['parameters']['values'] is None or \ len(report['parameters']['values']) == 0 or \ timestamps_data_all_equal_0(report['parameters']['timestamps']): has_parameters_names_and_timestamps_and_values_data = False if has_parameters_names_and_timestamps_and_values_data: ############################### # new worksheet ############################### parameters_data = report['parameters'] parameters_names_len = len(parameters_data['names']) parameters_ws = wb.create_sheet('相关参数') parameters_timestamps_data_max_len = \ get_parameters_timestamps_lists_max_len(list(parameters_data['timestamps'])) # Row height parameters_ws.row_dimensions[1].height = 102 for i in range(2, 7 + 1): parameters_ws.row_dimensions[i].height = 42 for i in range(8, parameters_timestamps_data_max_len + 10): parameters_ws.row_dimensions[i].height = 60 # Col width parameters_ws.column_dimensions['A'].width = 1.5 parameters_ws.column_dimensions['B'].width = 25.0 for i in range(3, 12 + parameters_names_len * 3): parameters_ws.column_dimensions[format_cell.get_column_letter( i)].width = 15.0 # Img img = Image("excelexporters/myems.png") img.width = img.width * 0.85 img.height = img.height * 0.85 # img = Image("myems.png") parameters_ws.add_image(img, 'B1') # Title parameters_ws.row_dimensions[3].height = 60 parameters_ws['B3'].font = name_font parameters_ws['B3'].alignment = b_r_alignment parameters_ws['B3'] = 'Name:' parameters_ws['C3'].border = b_border parameters_ws['C3'].alignment = b_c_alignment parameters_ws['C3'].font = name_font parameters_ws['C3'] = name parameters_ws['D3'].font = name_font parameters_ws['D3'].alignment = b_r_alignment parameters_ws['D3'] = 'Period:' parameters_ws['E3'].border = b_border parameters_ws['E3'].alignment = b_c_alignment parameters_ws['E3'].font = name_font parameters_ws['E3'] = period_type parameters_ws['F3'].font = name_font parameters_ws['F3'].alignment = b_r_alignment parameters_ws['F3'] = 'Date:' parameters_ws['G3'].border = b_border parameters_ws['G3'].alignment = b_c_alignment parameters_ws['G3'].font = name_font parameters_ws[ 'G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local parameters_ws.merge_cells("G3:H3") parameters_ws_current_row_number = 6 parameters_ws['B' + str(parameters_ws_current_row_number)].font = title_font parameters_ws['B' + str(parameters_ws_current_row_number)] = name + ' 相关参数' parameters_ws_current_row_number += 1 parameters_table_start_row_number = parameters_ws_current_row_number parameters_ws.row_dimensions[ parameters_ws_current_row_number].height = 80 parameters_ws_current_row_number += 1 table_current_col_number = 2 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border parameters_ws[col + str(parameters_ws_current_row_number - 1)].font = name_font parameters_ws[col + str(parameters_ws_current_row_number - 1)].alignment = c_c_alignment parameters_ws[col + str(parameters_ws_current_row_number - 1)] = parameters_data['names'][i] table_current_row_number = parameters_ws_current_row_number for j, value in enumerate(list(parameters_data['timestamps'][i])): col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = value col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = round( parameters_data['values'][i][j], 2) table_current_row_number += 1 table_current_col_number = table_current_col_number + 3 ######################################################## # parameters chart and parameters table ######################################################## ws['B' + str(current_sheet_parameters_row_number)].font = title_font ws['B' + str(current_sheet_parameters_row_number)] = name + ' 相关参数' current_sheet_parameters_row_number += 1 chart_start_row_number = current_sheet_parameters_row_number col_index = 0 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue line = LineChart() data_col = 3 + col_index * 3 labels_col = 2 + col_index * 3 col_index += 1 line.title = '相关参数 - ' + \ parameters_ws.cell(row=parameters_table_start_row_number, column=data_col).value labels = Reference(parameters_ws, min_col=labels_col, min_row=parameters_table_start_row_number + 1, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line_data = Reference( parameters_ws, min_col=data_col, min_row=parameters_table_start_row_number, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = False line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number) chart_start_row_number += 6 ws.add_chart(line, chart_cell) current_sheet_parameters_row_number = chart_start_row_number current_sheet_parameters_row_number += 1 filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active # Row height ws.row_dimensions[1].height = 118 for i in range(2, 37 + 1): ws.row_dimensions[i].height = 30 for i in range(38, 90 + 1): ws.row_dimensions[i].height = 30 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 20.0 for i in range(ord('C'), ord('I')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Constantia', size=15, bold=True) title_font = Font(name='宋体', size=15, bold=True) data_font = Font(name='Franklin Gothic Book', size=11) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000')) b_border = Border(bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) c_r_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") # img = Image("myems.png") ws.add_image(img, 'B1') # Title ws['B3'].font = name_font ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'].font = name_font ws['C3'] = name ws['D3'].font = name_font ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'].font = name_font ws['E3'] = period_type ws['F3'].font = name_font ws['F3'].alignment = b_r_alignment ws['F3'] = 'Date:' ws['G3'].border = b_border ws['G3'].alignment = b_c_alignment ws['G3'].font = name_font ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local ws.merge_cells("G3:H3") if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename ################################################# # First: 能耗分析 # 6: title # 7: table title # 8~10 table_data # Total: 5 rows # if has not energy data: set low height for rows ################################################# reporting_period_data = report['reporting_period'] has_energy_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_energy_data_flag = False if has_energy_data_flag: ws['B6'].font = title_font ws['B6'] = name + ' 能耗分析' category = reporting_period_data['names'] ca_len = len(category) ws['B7'].fill = table_fill ws['B8'].font = title_font ws['B8'].alignment = c_c_alignment ws['B8'] = '能耗' ws['B8'].border = f_border ws['B9'].font = title_font ws['B9'].alignment = c_c_alignment ws['B9'] = '单位面积能耗' ws['B9'].border = f_border ws['B10'].font = title_font ws['B10'].alignment = c_c_alignment ws['B10'] = '环比' ws['B10'].border = f_border for i in range(0, ca_len): col = chr(ord('C') + i) row = '7' cell = col + row ws[col + '7'].fill = table_fill ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = round(reporting_period_data['subtotals'][i], 0) ws[col + '8'].border = f_border ws[col + '9'].font = name_font ws[col + '9'].alignment = c_c_alignment ws[col + '9'] = round( reporting_period_data['subtotals_per_unit_area'][i], 2) ws[col + '9'].border = f_border ws[col + '10'].font = name_font ws[col + '10'].alignment = c_c_alignment ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \ if reporting_period_data['increment_rates'][i] is not None else "-" ws[col + '10'].border = f_border # TCE TCO2E end_col = col # TCE tce_col = chr(ord(end_col) + 1) ws[tce_col + '7'].fill = table_fill ws[tce_col + '7'].font = name_font ws[tce_col + '7'].alignment = c_c_alignment ws[tce_col + '7'] = "TCE" ws[tce_col + '7'].border = f_border ws[tce_col + '8'].font = name_font ws[tce_col + '8'].alignment = c_c_alignment ws[tce_col + '8'] = round(reporting_period_data['total_in_kgce'], 0) ws[tce_col + '8'].border = f_border ws[tce_col + '9'].font = name_font ws[tce_col + '9'].alignment = c_c_alignment ws[tce_col + '9'] = round( reporting_period_data['total_in_kgce_per_unit_area'], 2) ws[tce_col + '9'].border = f_border ws[tce_col + '10'].font = name_font ws[tce_col + '10'].alignment = c_c_alignment ws[tce_col + '10'] = str(round(reporting_period_data['increment_rate_in_kgce'] * 100, 2)) + "%" \ if reporting_period_data['increment_rate_in_kgce'] is not None else "-" ws[tce_col + '10'].border = f_border # TCO2E tco2e_col = chr(ord(end_col) + 2) ws[tco2e_col + '7'].fill = table_fill ws[tco2e_col + '7'].font = name_font ws[tco2e_col + '7'].alignment = c_c_alignment ws[tco2e_col + '7'] = "TCO2E" ws[tco2e_col + '7'].border = f_border ws[tco2e_col + '8'].font = name_font ws[tco2e_col + '8'].alignment = c_c_alignment ws[tco2e_col + '8'] = round(reporting_period_data['total_in_kgco2e'], 0) ws[tco2e_col + '8'].border = f_border ws[tco2e_col + '9'].font = name_font ws[tco2e_col + '9'].alignment = c_c_alignment ws[tco2e_col + '9'] = round( reporting_period_data['total_in_kgco2e_per_unit_area'], 2) ws[tco2e_col + '9'].border = f_border ws[tco2e_col + '10'].font = name_font ws[tco2e_col + '10'].alignment = c_c_alignment ws[tco2e_col + '10'] = str(round(reporting_period_data['increment_rate_in_kgco2e'] * 100, 2)) + "%" \ if reporting_period_data['increment_rate_in_kgco2e'] is not None else "-" ws[tco2e_col + '10'].border = f_border else: for i in range(6, 10 + 1): ws.row_dimensions[i].height = 0.1 ################################################# # Second: 分时电耗 # 12: title # 13: table title # 14~17 table_data # Total: 6 rows ################################################ has_ele_peak_flag = True if "toppeaks" not in reporting_period_data.keys() or \ reporting_period_data['toppeaks'] is None or \ len(reporting_period_data['toppeaks']) == 0: has_ele_peak_flag = False if has_ele_peak_flag: ws['B12'].font = title_font ws['B12'] = name + ' 分时电耗' ws['B13'].fill = table_fill ws['B13'].font = name_font ws['B13'].alignment = c_c_alignment ws['B13'].border = f_border ws['C13'].fill = table_fill ws['C13'].font = name_font ws['C13'].alignment = c_c_alignment ws['C13'].border = f_border ws['C13'] = '分时电耗' ws['B14'].font = title_font ws['B14'].alignment = c_c_alignment ws['B14'] = '尖' ws['B14'].border = f_border ws['C14'].font = title_font ws['C14'].alignment = c_c_alignment ws['C14'].border = f_border ws['C14'] = round(reporting_period_data['toppeaks'][0], 0) ws['B15'].font = title_font ws['B15'].alignment = c_c_alignment ws['B15'] = '峰' ws['B15'].border = f_border ws['C15'].font = title_font ws['C15'].alignment = c_c_alignment ws['C15'].border = f_border ws['C15'] = round(reporting_period_data['onpeaks'][0], 0) ws['B16'].font = title_font ws['B16'].alignment = c_c_alignment ws['B16'] = '平' ws['B16'].border = f_border ws['C16'].font = title_font ws['C16'].alignment = c_c_alignment ws['C16'].border = f_border ws['C16'] = round(reporting_period_data['midpeaks'][0], 0) ws['B17'].font = title_font ws['B17'].alignment = c_c_alignment ws['B17'] = '谷' ws['B17'].border = f_border ws['C17'].font = title_font ws['C17'].alignment = c_c_alignment ws['C17'].border = f_border ws['C17'] = round(reporting_period_data['offpeaks'][0], 0) pie = PieChart() labels = Reference(ws, min_col=2, min_row=14, max_row=17) pie_data = Reference(ws, min_col=3, min_row=14, max_row=17) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 5.25 # cm 1.05*5 1.05cm = 30 pt pie.width = 9 # pie.title = "Pies sold by category" s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False # 标签显示 s1.dLbls.showVal = True # 数量显示 s1.dLbls.showPercent = True # 百分比显示 # s1 = CharacterProperties(sz=1800) # 图表中字体大小 *100 ws.add_chart(pie, "D13") else: for i in range(12, 18 + 1): ws.row_dimensions[i].height = 0.1 # end_row 10 # start_row 12 ################################################ # Third: 子空间能耗 # 19: title # 20: table title # 21~24 table_data # Total: 6 rows ################################################ has_child_flag = True # Judge if the space has child space, if not, delete it. if "child_space" not in report.keys() or "energy_category_names" not in report['child_space'].keys() or \ len(report['child_space']["energy_category_names"]) == 0: has_child_flag = False if has_child_flag: child = report['child_space'] child_spaces = child['child_space_names_array'][0] child_subtotals = child['subtotals_array'][0] ws['B19'].font = title_font ws['B19'] = name + ' 子空间能耗' ws['B20'].fill = table_fill ws['B20'].border = f_border ca_len = len(child['energy_category_names']) for i in range(0, ca_len): row = chr(ord('C') + i) ws[row + '20'].fill = table_fill ws[row + '20'].font = title_font ws[row + '20'].alignment = c_c_alignment ws[row + '20'].border = f_border ws[row + '20'] = child['energy_category_names'][i] space_len = len(child['child_space_names_array'][0]) for i in range(0, space_len): row = str(i + 21) ws['B' + row].font = name_font ws['B' + row].alignment = c_c_alignment ws['B' + row] = child['child_space_names_array'][0][i] ws['B' + row].border = f_border for j in range(0, ca_len): col = chr(ord('C') + j) ws[col + row].font = name_font ws[col + row].alignment = c_c_alignment ws[col + row] = child['subtotals_array'][j][i] ws[col + row].border = f_border # pie # 25~30: pie pie = PieChart() labels = Reference(ws, min_col=2, min_row=21, max_row=23) pie_data = Reference(ws, min_col=3 + j, min_row=21, max_row=23) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 5.25 # cm 1.05*5 1.05cm = 30 pt pie.width = 8 # pie.title = "Pies sold by category" s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = True # 标签显示 s1.dLbls.showVal = True # 数量显示 s1.dLbls.showPercent = True # 百分比显示 # s1 = CharacterProperties(sz=1800) # 图表中字体大小 *100 chart_col = chr(ord('B') + 2 * j) chart_cell = chart_col + '26' ws.add_chart(pie, chart_cell) else: for i in range(19, 36 + 1): ws.row_dimensions[i].height = 0.1 for i in range(31, 35 + 1): ws.row_dimensions[i].height = 0.1 ################################################ # Fourth: 能耗详情 # 37: title # 38~ 38+ca_len*5-1: bar # 38+ca_len*5: table title # 38+ca_len*5~: table_data ################################################ reporting_period_data = report['reporting_period'] times = reporting_period_data['timestamps'] has_detail_data_flag = True ca_len = len(report['reporting_period']['names']) table_row = 38 + ca_len * 5 if "timestamps" not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0: has_detail_data_flag = False if has_detail_data_flag: ws['B37'].font = title_font ws['B37'] = name + ' 能耗详情' ws['B' + str(table_row)].fill = table_fill ws['B' + str(table_row)].border = f_border ws['B' + str(table_row)].alignment = c_c_alignment ws['B' + str(table_row)] = '时间' time = times[0] has_data = False max_row = 0 if len(time) > 0: has_data = True max_row = table_row + len(time) print("max_row", max_row) if has_data: for i in range(0, len(time)): col = 'B' row = str(table_row + 1 + i) # col = chr(ord('B') + i) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = time[i] ws[col + row].border = f_border for i in range(0, ca_len): # 38 title col = chr(ord('C') + i) ws[col + str(table_row)].fill = table_fill ws[col + str(table_row)].font = title_font ws[col + str(table_row)].alignment = c_c_alignment ws[col + str(table_row)] = reporting_period_data['names'][i] + \ " (" + reporting_period_data['units'][i] + ")" ws[col + str(table_row)].border = f_border # 39 data time = times[i] time_len = len(time) for j in range(0, time_len): row = str(table_row + 1 + j) # col = chr(ord('B') + i) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round( reporting_period_data['values'][i][j], 0) ws[col + row].border = f_border # bar # 39~: bar bar = BarChart() labels = Reference(ws, min_col=2, min_row=table_row + 1, max_row=max_row + 1) bar_data = Reference(ws, min_col=3 + i, min_row=table_row, max_row=max_row + 1) # openpyxl bug bar.add_data(bar_data, titles_from_data=True) bar.set_categories(labels) bar.height = 5.25 # cm 1.05*5 1.05cm = 30 pt bar.width = 18 # pie.title = "Pies sold by category" bar.dLbls = DataLabelList() # bar.dLbls.showCatName = True # label show bar.dLbls.showVal = True # val show bar.dLbls.showPercent = True # percent show # s1 = CharacterProperties(sz=1800) # font size *100 chart_col = 'B' chart_cell = chart_col + str(38 + 5 * i) ws.add_chart(bar, chart_cell) else: for i in range(37, 69 + 1): ws.row_dimensions[i].height = 0.1 filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active # Row height ws.row_dimensions[1].height = 118 for i in range(2, 37 + 1): ws.row_dimensions[i].height = 30 for i in range(38, 69 + 1): ws.row_dimensions[i].height = 30 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('I')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Constantia', size=15, bold=True) title_font = Font(name='宋体', size=15, bold=True) data_font = Font(name='Franklin Gothic Book', size=11) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000')) b_border = Border(bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) c_r_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") # img = Image("myems.png") ws.add_image(img, 'B1') # Title ws['B3'].font = name_font ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'].font = name_font ws['C3'] = name ws['D3'].font = name_font ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'].font = name_font ws['E3'] = period_type ws['F3'].font = name_font ws['F3'].alignment = b_r_alignment ws['F3'] = 'Date:' ws.merge_cells("G3:H3") ws['G3'].border = b_border ws['G3'].alignment = b_c_alignment ws['G3'].font = name_font ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename ################################## reporting_period_data = report['reporting_period'] has_cost_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_cost_data_flag = False if has_cost_data_flag: ws['B6'].font = title_font ws['B6'] = name + ' 报告期成本' category = reporting_period_data['names'] ca_len = len(category) ws['B7'].fill = table_fill ws['B8'].font = title_font ws['B8'].alignment = c_c_alignment ws['B8'] = '成本' ws['B8'].border = f_border ws['B9'].font = title_font ws['B9'].alignment = c_c_alignment ws['B9'] = '单位面积值' ws['B9'].border = f_border ws['B10'].font = title_font ws['B10'].alignment = c_c_alignment ws['B10'] = '环比' ws['B10'].border = f_border for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + '7'].fill = table_fill ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = round(reporting_period_data['subtotals'][i], 0) ws[col + '8'].border = f_border ws[col + '9'].font = name_font ws[col + '9'].alignment = c_c_alignment ws[col + '9'] = round( reporting_period_data['subtotals_per_unit_area'][i], 2) ws[col + '9'].border = f_border ws[col + '10'].font = name_font ws[col + '10'].alignment = c_c_alignment ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \ if reporting_period_data['increment_rates'][i] is not None else "-" ws[col + '10'].border = f_border else: for i in range(6, 10 + 1): ws.row_dimensions[i].height = 0.1 ############################## has_ele_peak_flag = True if "toppeaks" not in reporting_period_data.keys() or \ reporting_period_data['toppeaks'] is None or \ len(reporting_period_data['toppeaks']) == 0: has_ele_peak_flag = False if has_ele_peak_flag: ws['B12'].font = title_font ws['B12'] = name + '分时用电成本' ws['B13'].fill = table_fill ws['B13'].font = name_font ws['B13'].alignment = c_c_alignment ws['B13'].border = f_border ws['C13'].fill = table_fill ws['C13'].font = name_font ws['C13'].alignment = c_c_alignment ws['C13'].border = f_border ws['C13'] = '分时用电成本' ws['B14'].font = title_font ws['B14'].alignment = c_c_alignment ws['B14'] = '尖' ws['B14'].border = f_border ws['C14'].font = title_font ws['C14'].alignment = c_c_alignment ws['C14'].border = f_border ws['C14'] = round(reporting_period_data['toppeaks'][0], 0) ws['B15'].font = title_font ws['B15'].alignment = c_c_alignment ws['B15'] = '峰' ws['B15'].border = f_border ws['C15'].font = title_font ws['C15'].alignment = c_c_alignment ws['C15'].border = f_border ws['C15'] = round(reporting_period_data['onpeaks'][0], 0) ws['B16'].font = title_font ws['B16'].alignment = c_c_alignment ws['B16'] = '平' ws['B16'].border = f_border ws['C16'].font = title_font ws['C16'].alignment = c_c_alignment ws['C16'].border = f_border ws['C16'] = round(reporting_period_data['midpeaks'][0], 0) ws['B17'].font = title_font ws['B17'].alignment = c_c_alignment ws['B17'] = '谷' ws['B17'].border = f_border ws['C17'].font = title_font ws['C17'].alignment = c_c_alignment ws['C17'].border = f_border ws['C17'] = round(reporting_period_data['offpeaks'][0], 0) pie = PieChart() labels = Reference(ws, min_col=2, min_row=14, max_row=17) pie_data = Reference(ws, min_col=3, min_row=13, max_row=17) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 5.25 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True ws.add_chart(pie, "D13") else: for i in range(12, 18 + 1): ws.row_dimensions[i].height = 0.1 ################################## current_row_number = 19 has_child_flag = True if "child_space" not in report.keys() or "energy_category_names" not in report['child_space'].keys() or \ len(report['child_space']["energy_category_names"]) == 0: has_child_flag = False if has_child_flag: child = report['child_space'] ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 子空间数据' current_row_number += 1 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].border = f_border ca_len = len(child['energy_category_names']) for i in range(0, ca_len): row = chr(ord('C') + i) ws[row + str(current_row_number)].fill = table_fill ws[row + str(current_row_number)].font = title_font ws[row + str(current_row_number)].alignment = c_c_alignment ws[row + str(current_row_number)].border = f_border ws[row + str(current_row_number)] = child['energy_category_names'][i] space_len = len(child['child_space_names_array'][0]) for i in range(0, space_len): current_row_number += 1 row = str(current_row_number) ws['B' + row].font = name_font ws['B' + row].alignment = c_c_alignment ws['B' + row] = child['child_space_names_array'][0][i] ws['B' + row].border = f_border for j in range(0, ca_len): col = chr(ord('C') + j) ws[col + row].font = name_font ws[col + row].alignment = c_c_alignment ws[col + row] = child['subtotals_array'][j][i] ws[col + row].border = f_border current_row_number += 1 # Pie for i in range(0, ca_len): pie = PieChart() labels = Reference(ws, min_col=2, min_row=current_row_number - space_len, max_row=current_row_number - 1) pie_data = Reference(ws, min_col=3 + i, min_row=current_row_number - space_len - 1, max_row=current_row_number - 1) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 5.25 pie.width = 8 col = chr(ord('C') + i) pie.title = ws[col + '20'].value s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True chart_col = chr(ord('B') + 2 * i) chart_cell = chart_col + str(current_row_number) ws.add_chart(pie, chart_cell) current_row_number += 5 else: for i in range(19, 36 + 1): current_row_number = 36 ws.row_dimensions[i].height = 0.1 current_row_number += 1 ############################################# reporting_period_data = report['reporting_period'] times = reporting_period_data['timestamps'] has_detail_data_flag = True ca_len = len(report['reporting_period']['names']) table_row = (current_row_number + 1) + ca_len * 5 if "timestamps" not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0: has_detail_data_flag = False if has_detail_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 详细数据' ws['B' + str(table_row)].fill = table_fill ws['B' + str(table_row)].border = f_border ws['B' + str(table_row)].alignment = c_c_alignment ws['B' + str(table_row)] = '日期时间' time = times[0] has_data = False max_row = 0 if len(time) > 0: has_data = True max_row = table_row + len(time) if has_data: for i in range(0, len(time)): col = 'B' row = str(table_row + 1 + i) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = time[i] ws[col + row].border = f_border for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(table_row)].fill = table_fill ws[col + str(table_row)].font = title_font ws[col + str(table_row)].alignment = c_c_alignment ws[col + str(table_row)] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + str(table_row)].border = f_border # 39 data time = times[i] time_len = len(time) for j in range(0, time_len): row = str(table_row + 1 + j) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round( reporting_period_data['values'][i][j], 0) ws[col + row].border = f_border bar = BarChart() labels = Reference(ws, min_col=2, min_row=table_row + 1, max_row=max_row) bar_data = Reference(ws, min_col=3 + i, min_row=table_row, max_row=max_row) bar.add_data(bar_data, titles_from_data=True) bar.set_categories(labels) bar.height = 5.25 bar.width = 18 bar.dLbls = DataLabelList() bar.dLbls.showVal = True bar.dLbls.showPercent = True chart_col = 'B' chart_cell = chart_col + str(current_row_number + 1 + 5 * i) ws.add_chart(bar, chart_cell) else: for i in range(37, 69 + 1): ws.row_dimensions[i].height = 0.1 filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active # Row height ws.row_dimensions[1].height = 118 for i in range(2, 37 + 1): ws.row_dimensions[i].height = 30 for i in range(38, 90 + 1): ws.row_dimensions[i].height = 30 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 20.0 ws.column_dimensions['C'].width = 20.0 for i in range(ord('D'), ord('I')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Constantia', size=15, bold=True) title_font = Font(name='宋体', size=15, bold=True) data_font = Font(name='Franklin Gothic Book', size=11) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000')) b_border = Border(bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) c_r_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") # img = Image("myems.png") ws.add_image(img, 'B1') # Title ws['B3'].font = name_font ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'].font = name_font ws['C3'] = name ws['D3'].font = name_font ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'].font = name_font ws['E3'] = period_type ws['F3'].font = name_font ws['F3'].alignment = b_r_alignment ws['F3'] = 'Date:' ws.merge_cells("G3:J3") for i in range(ord('G'), ord('J') + 1): ws[chr(i) + '3'].border = b_border ws['G3'].alignment = b_c_alignment ws['G3'].font = name_font ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename ################################################# reporting_period_data = report['reporting_period'] has_energy_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_energy_data_flag = False if has_energy_data_flag: ws['B6'].font = title_font ws['B6'] = name + ' 报告期成本' category = reporting_period_data['names'] ca_len = len(category) ws['B7'].fill = table_fill ws['B8'].font = title_font ws['B8'].alignment = c_c_alignment ws['B8'] = '成本' ws['B8'].border = f_border ws['B9'].font = title_font ws['B9'].alignment = c_c_alignment ws['B9'] = '单位面积能耗' ws['B9'].border = f_border ws['B10'].font = title_font ws['B10'].alignment = c_c_alignment ws['B10'] = '环比' ws['B10'].border = f_border col = 'B' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + '7'].fill = table_fill ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = round(reporting_period_data['subtotals'][i], 0) ws[col + '8'].border = f_border ws[col + '9'].font = name_font ws[col + '9'].alignment = c_c_alignment ws[col + '9'] = round( reporting_period_data['subtotals_per_unit_area'][i], 2) ws[col + '9'].border = f_border ws[col + '10'].font = name_font ws[col + '10'].alignment = c_c_alignment ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \ if reporting_period_data['increment_rates'][i] is not None else "-" ws[col + '10'].border = f_border end_col = chr(ord(col) + 1) ws[end_col + '7'].fill = table_fill ws[end_col + '7'].font = name_font ws[end_col + '7'].alignment = c_c_alignment ws[end_col + '7'] = "总计 (" + reporting_period_data['total_unit'] + ")" ws[end_col + '7'].border = f_border ws[end_col + '8'].font = name_font ws[end_col + '8'].alignment = c_c_alignment ws[end_col + '8'] = round(reporting_period_data['total'], 0) ws[end_col + '8'].border = f_border ws[end_col + '9'].font = name_font ws[end_col + '9'].alignment = c_c_alignment ws[end_col + '9'] = round(reporting_period_data['total_per_unit_area'], 2) ws[end_col + '9'].border = f_border ws[end_col + '10'].font = name_font ws[end_col + '10'].alignment = c_c_alignment ws[end_col + '10'] = str(round(reporting_period_data['total_increment_rate'] * 100, 2)) + "%" \ if reporting_period_data['total_increment_rate'] is not None else "-" ws[end_col + '10'].border = f_border else: for i in range(6, 10 + 1): ws.row_dimensions[i].height = 0.1 ################################################# has_ele_peak_flag = True if "toppeaks" not in reporting_period_data.keys() or \ reporting_period_data['toppeaks'] is None or \ len(reporting_period_data['toppeaks']) == 0: has_ele_peak_flag = False if has_ele_peak_flag: ws['B12'].font = title_font ws['B12'] = name + ' 分时电耗' ws['B13'].fill = table_fill ws['B13'].font = name_font ws['B13'].alignment = c_c_alignment ws['B13'].border = f_border ws['C13'].fill = table_fill ws['C13'].font = name_font ws['C13'].alignment = c_c_alignment ws['C13'].border = f_border ws['C13'] = '分时电耗' ws['B14'].font = title_font ws['B14'].alignment = c_c_alignment ws['B14'] = '尖' ws['B14'].border = f_border ws['C14'].font = title_font ws['C14'].alignment = c_c_alignment ws['C14'].border = f_border ws['C14'] = round(reporting_period_data['toppeaks'][0], 0) ws['B15'].font = title_font ws['B15'].alignment = c_c_alignment ws['B15'] = '峰' ws['B15'].border = f_border ws['C15'].font = title_font ws['C15'].alignment = c_c_alignment ws['C15'].border = f_border ws['C15'] = round(reporting_period_data['onpeaks'][0], 0) ws['B16'].font = title_font ws['B16'].alignment = c_c_alignment ws['B16'] = '平' ws['B16'].border = f_border ws['C16'].font = title_font ws['C16'].alignment = c_c_alignment ws['C16'].border = f_border ws['C16'] = round(reporting_period_data['midpeaks'][0], 0) ws['B17'].font = title_font ws['B17'].alignment = c_c_alignment ws['B17'] = '谷' ws['B17'].border = f_border ws['C17'].font = title_font ws['C17'].alignment = c_c_alignment ws['C17'].border = f_border ws['C17'] = round(reporting_period_data['offpeaks'][0], 0) pie = PieChart() labels = Reference(ws, min_col=2, min_row=14, max_row=17) pie_data = Reference(ws, min_col=3, min_row=13, max_row=17) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 5.25 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True ws.add_chart(pie, "D13") else: for i in range(12, 18 + 1): ws.row_dimensions[i].height = 0.1 ################################################ current_row_number = 19 has_subtotals_data_flag = True if "subtotals" not in reporting_period_data.keys() or \ reporting_period_data['subtotals'] is None or \ len(reporting_period_data['subtotals']) == 0: has_subtotals_data_flag = False if has_subtotals_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 成本占比' current_row_number += 1 table_start_row_number = current_row_number ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = name_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = '成本占比' current_row_number += 1 ca_len = len(reporting_period_data['names']) for i in range(0, ca_len): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = reporting_period_data['names'][i] ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].font = title_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) current_row_number += 1 table_end_row_number = current_row_number - 1 pie = PieChart() labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 5.25 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True table_cell = 'D' + str(table_start_row_number) ws.add_chart(pie, table_cell) if ca_len < 4: current_row_number = current_row_number - ca_len + 4 else: for i in range(21, 29 + 1): current_row_number = 30 ws.row_dimensions[i].height = 0.1 ############################################### current_row_number += 1 has_detail_data_flag = True table_start_draw_flag = current_row_number + 1 if "timestamps" not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0: has_detail_data_flag = False if has_detail_data_flag: reporting_period_data = report['reporting_period'] times = reporting_period_data['timestamps'] ca_len = len(report['reporting_period']['names']) ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 详细数据' table_start_row_number = (current_row_number + 1) + ca_len * 5 current_row_number = table_start_row_number time = times[0] has_data = False if len(time) > 0: has_data = True if has_data: ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = '日期时间' col = 'B' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)] = reporting_period_data['names'][i] + \ " (" + reporting_period_data['units'][i] + ")" ws[col + str(current_row_number)].border = f_border end_col = chr(ord(col) + 1) ws[end_col + str(current_row_number)].fill = table_fill ws[end_col + str(current_row_number)].font = title_font ws[end_col + str(current_row_number)].alignment = c_c_alignment ws[end_col + str(current_row_number )] = "总计 (" + reporting_period_data['total_unit'] + ")" ws[end_col + str(current_row_number)].border = f_border current_row_number += 1 for i in range(0, len(time)): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = time[i] ws['B' + str(current_row_number)].border = f_border col = 'B' every_day_total = 0 for j in range(0, ca_len): col = chr(ord('C') + j) ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment value = round(reporting_period_data['values'][j][i], 0) every_day_total += value ws[col + str(current_row_number)] = value ws[col + str(current_row_number)].border = f_border end_col = chr(ord(col) + 1) ws[end_col + str(current_row_number)].font = title_font ws[end_col + str(current_row_number)].alignment = c_c_alignment ws[end_col + str(current_row_number)] = round( every_day_total, 0) ws[end_col + str(current_row_number)].border = f_border current_row_number += 1 table_end_row_number = current_row_number - 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = '小计' ws['B' + str(current_row_number)].border = f_border col = 'B' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 0) ws[col + str(current_row_number)].border = f_border # bar bar = BarChart() labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) bar_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number) bar.add_data(bar_data, titles_from_data=True) bar.set_categories(labels) bar.height = 5.25 bar.width = len(time) bar.dLbls = DataLabelList() bar.dLbls.showVal = True bar.dLbls.showPercent = True chart_col = 'B' chart_cell = chart_col + str(table_start_draw_flag + 5 * i) ws.add_chart(bar, chart_cell) end_col = chr(ord(col) + 1) ws[end_col + str(current_row_number)].font = title_font ws[end_col + str(current_row_number)].alignment = c_c_alignment ws[end_col + str(current_row_number)] = round( reporting_period_data['total'], 0) ws[end_col + str(current_row_number)].border = f_border current_row_number += 1 else: for i in range(30, 69 + 1): current_row_number = 70 ws.row_dimensions[i].height = 0.1 filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active ws.title = "StoreCost" # Row height ws.row_dimensions[1].height = 118 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 42 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 20.0 ws.column_dimensions['C'].width = 20.0 for i in range(ord('D'), ord('I')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Arial', size=15, bold=True) title_font = Font(name='Arial', size=15, bold=True) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000')) b_border = Border(bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") ws.add_image(img, 'A1') # Title ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'] = name ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'] = period_type ws['B4'].alignment = b_r_alignment ws['B4'] = 'Reporting Start Datetime:' ws['C4'].border = b_border ws['C4'].alignment = b_c_alignment ws['C4'] = reporting_start_datetime_local ws['D4'].alignment = b_r_alignment ws['D4'] = 'Reporting End Datetime:' ws['E4'].border = b_border ws['E4'].alignment = b_c_alignment ws['E4'] = reporting_end_datetime_local if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename #################################################################################################################### reporting_period_data = report['reporting_period'] has_energy_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_energy_data_flag = False if has_energy_data_flag: ws['B6'].font = title_font ws['B6'] = name + ' ' + 'Reporting Period Costs' category = reporting_period_data['names'] ca_len = len(category) ws['B7'].fill = table_fill ws['B8'].font = title_font ws['B8'].alignment = c_c_alignment ws['B8'] = 'Cost' ws['B8'].border = f_border ws['B9'].font = title_font ws['B9'].alignment = c_c_alignment ws['B9'] = 'Per Unit Area' ws['B9'].border = f_border ws['B10'].font = title_font ws['B10'].alignment = c_c_alignment ws['B10'] = 'Increment Rate' ws['B10'].border = f_border col = 'B' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + '7'].fill = table_fill ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = round(reporting_period_data['subtotals'][i], 2) ws[col + '8'].border = f_border ws[col + '9'].font = name_font ws[col + '9'].alignment = c_c_alignment ws[col + '9'] = round( reporting_period_data['subtotals_per_unit_area'][i], 2) ws[col + '9'].border = f_border ws[col + '10'].font = name_font ws[col + '10'].alignment = c_c_alignment ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \ if reporting_period_data['increment_rates'][i] is not None else "-" ws[col + '10'].border = f_border end_col = chr(ord(col) + 1) ws[end_col + '7'].fill = table_fill ws[end_col + '7'].font = name_font ws[end_col + '7'].alignment = c_c_alignment ws[end_col + '7'] = "Total (" + reporting_period_data['total_unit'] + ")" ws[end_col + '7'].border = f_border ws[end_col + '8'].font = name_font ws[end_col + '8'].alignment = c_c_alignment ws[end_col + '8'] = round(reporting_period_data['total'], 2) ws[end_col + '8'].border = f_border ws[end_col + '9'].font = name_font ws[end_col + '9'].alignment = c_c_alignment ws[end_col + '9'] = round(reporting_period_data['total_per_unit_area'], 2) ws[end_col + '9'].border = f_border ws[end_col + '10'].font = name_font ws[end_col + '10'].alignment = c_c_alignment ws[end_col + '10'] = str(round(reporting_period_data['total_increment_rate'] * 100, 2)) + "%" \ if reporting_period_data['total_increment_rate'] is not None else "-" ws[end_col + '10'].border = f_border else: for i in range(6, 10 + 1): ws.row_dimensions[i].height = 0.1 #################################################################################################################### has_ele_peak_flag = True if "toppeaks" not in reporting_period_data.keys() or \ reporting_period_data['toppeaks'] is None or \ len(reporting_period_data['toppeaks']) == 0: has_ele_peak_flag = False if has_ele_peak_flag: ws['B12'].font = title_font ws['B12'] = name + ' ' + 'Electricity Consumption by Time-Of-Use' ws['B13'].fill = table_fill ws['B13'].font = name_font ws['B13'].alignment = c_c_alignment ws['B13'].border = f_border ws['C13'].fill = table_fill ws['C13'].font = name_font ws['C13'].alignment = c_c_alignment ws['C13'].border = f_border ws['C13'] = 'Electricity Consumption by Time-Of-Use' ws['B14'].font = title_font ws['B14'].alignment = c_c_alignment ws['B14'] = 'TopPeak' ws['B14'].border = f_border ws['C14'].font = title_font ws['C14'].alignment = c_c_alignment ws['C14'].border = f_border ws['C14'] = round(reporting_period_data['toppeaks'][0], 2) ws['B15'].font = title_font ws['B15'].alignment = c_c_alignment ws['B15'] = 'OnPeak' ws['B15'].border = f_border ws['C15'].font = title_font ws['C15'].alignment = c_c_alignment ws['C15'].border = f_border ws['C15'] = round(reporting_period_data['onpeaks'][0], 2) ws['B16'].font = title_font ws['B16'].alignment = c_c_alignment ws['B16'] = 'MidPeak' ws['B16'].border = f_border ws['C16'].font = title_font ws['C16'].alignment = c_c_alignment ws['C16'].border = f_border ws['C16'] = round(reporting_period_data['midpeaks'][0], 2) ws['B17'].font = title_font ws['B17'].alignment = c_c_alignment ws['B17'] = 'OffPeak' ws['B17'].border = f_border ws['C17'].font = title_font ws['C17'].alignment = c_c_alignment ws['C17'].border = f_border ws['C17'] = round(reporting_period_data['offpeaks'][0], 2) pie = PieChart() labels = Reference(ws, min_col=2, min_row=14, max_row=17) pie_data = Reference(ws, min_col=3, min_row=13, max_row=17) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 5.25 pie.width = 8 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True ws.add_chart(pie, "D13") else: for i in range(12, 18 + 1): ws.row_dimensions[i].height = 0.1 #################################################################################################################### current_row_number = 19 has_subtotals_data_flag = True if "subtotals" not in reporting_period_data.keys() or \ reporting_period_data['subtotals'] is None or \ len(reporting_period_data['subtotals']) == 0: has_subtotals_data_flag = False if has_subtotals_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + 'Costs Proportion' current_row_number += 1 table_start_row_number = current_row_number ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = name_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = 'Costs Proportion' current_row_number += 1 ca_len = len(reporting_period_data['names']) for i in range(0, ca_len): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = reporting_period_data['names'][i] ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].font = title_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) current_row_number += 1 table_end_row_number = current_row_number - 1 pie = PieChart() labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 5.25 pie.width = 8 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True table_cell = 'D' + str(table_start_row_number) ws.add_chart(pie, table_cell) if ca_len < 4: current_row_number = current_row_number - ca_len + 4 else: for i in range(21, 29 + 1): current_row_number = 30 ws.row_dimensions[i].height = 0.1 #################################################################################################################### has_detail_data_flag = True table_start_draw_flag = current_row_number + 1 if "timestamps" not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0: has_detail_data_flag = False if has_detail_data_flag: reporting_period_data = report['reporting_period'] times = reporting_period_data['timestamps'] ca_len = len(report['reporting_period']['names']) parameters_names_len = len(report['parameters']['names']) parameters_parameters_datas_len = 0 for i in range(0, parameters_names_len): if len(report['parameters']['timestamps'][i]) == 0: continue parameters_parameters_datas_len += 1 detail_data_table_start_row_number = current_row_number + ( ca_len + parameters_parameters_datas_len) * 6 + 3 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + 'Detailed Data' current_row_number = detail_data_table_start_row_number time = times[0] has_data = False if len(time) > 0: has_data = True if has_data: ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = 'Datetime' col = 'B' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)] = reporting_period_data['names'][i] + \ " (" + reporting_period_data['units'][i] + ")" ws[col + str(current_row_number)].border = f_border end_col = chr(ord(col) + 1) ws[end_col + str(current_row_number)].fill = table_fill ws[end_col + str(current_row_number)].font = title_font ws[end_col + str(current_row_number)].alignment = c_c_alignment ws[end_col + str(current_row_number )] = "Total (" + reporting_period_data['total_unit'] + ")" ws[end_col + str(current_row_number)].border = f_border current_row_number += 1 for i in range(0, len(time)): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = time[i] ws['B' + str(current_row_number)].border = f_border col = 'B' periodic_sum = Decimal(0.0) for j in range(0, ca_len): col = chr(ord('C') + j) ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment value = round(reporting_period_data['values'][j][i], 2) periodic_sum += value ws[col + str(current_row_number)] = value ws[col + str(current_row_number)].border = f_border end_col = chr(ord(col) + 1) ws[end_col + str(current_row_number)].font = title_font ws[end_col + str(current_row_number)].alignment = c_c_alignment ws[end_col + str(current_row_number)] = round(periodic_sum, 2) ws[end_col + str(current_row_number)].border = f_border current_row_number += 1 table_end_row_number = current_row_number - 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = 'Subtotal' ws['B' + str(current_row_number)].border = f_border col = 'B' format_time_width_number = 1.0 min_len_number = 1.0 min_width_number = 11.0 if period_type == 'hourly': format_time_width_number = 4.0 min_len_number = 2 min_width_number = 12.0 elif period_type == 'daily': format_time_width_number = 2.5 min_len_number = 4 min_width_number = 14.0 elif period_type == 'monthly': format_time_width_number = 2.1 min_len_number = 4 min_width_number = 12.4 elif period_type == 'yearly': format_time_width_number = 1.5 min_len_number = 5 min_width_number = 11.5 for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) ws[col + str(current_row_number)].border = f_border line = LineChart() line.title = 'Reporting Period Costs - ' + \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" labels = Reference(ws, min_col=2, min_row=detail_data_table_start_row_number + 1, max_row=table_end_row_number) line_data = Reference( ws, min_col=3 + i, min_row=detail_data_table_start_row_number, max_row=table_end_row_number) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.height = 8.25 line.width = format_time_width_number * len(time) if len( time) > min_len_number else min_width_number if line.width > 24: line.width = 24 line.x_axis.crosses = 'min' line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = True line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(table_start_draw_flag + 6 * i) ws.add_chart(line, chart_cell) end_col = chr(ord(col) + 1) ws[end_col + str(current_row_number)].font = title_font ws[end_col + str(current_row_number)].alignment = c_c_alignment ws[end_col + str(current_row_number)] = round( reporting_period_data['total'], 2) ws[end_col + str(current_row_number)].border = f_border current_row_number += 1 else: for i in range(30, 69 + 1): current_row_number = 70 ws.row_dimensions[i].height = 0.1 #################################################################################################################### has_parameters_names_and_timestamps_and_values_data = True ca_len = len(report['reporting_period']['names']) current_sheet_parameters_row_number = table_start_draw_flag + ca_len * 6 if 'parameters' not in report.keys() or \ report['parameters'] is None or \ 'names' not in report['parameters'].keys() or \ report['parameters']['names'] is None or \ len(report['parameters']['names']) == 0 or \ 'timestamps' not in report['parameters'].keys() or \ report['parameters']['timestamps'] is None or \ len(report['parameters']['timestamps']) == 0 or \ 'values' not in report['parameters'].keys() or \ report['parameters']['values'] is None or \ len(report['parameters']['values']) == 0 or \ timestamps_data_all_equal_0(report['parameters']['timestamps']): has_parameters_names_and_timestamps_and_values_data = False if has_parameters_names_and_timestamps_and_values_data: ################################################################################################################ # new worksheet ################################################################################################################ parameters_data = report['parameters'] parameters_names_len = len(parameters_data['names']) file_name = "Store" + re.sub(r'[^A-Z]', '', ws.title.strip('S')) + "_" parameters_ws = wb.create_sheet(file_name + 'Parameters') parameters_timestamps_data_max_len = \ get_parameters_timestamps_lists_max_len(list(parameters_data['timestamps'])) # Row height parameters_ws.row_dimensions[1].height = 102 for i in range(2, 7 + 1): parameters_ws.row_dimensions[i].height = 42 for i in range(8, parameters_timestamps_data_max_len + 10): parameters_ws.row_dimensions[i].height = 60 # Col width parameters_ws.column_dimensions['A'].width = 1.5 parameters_ws.column_dimensions['B'].width = 25.0 for i in range(3, 12 + parameters_names_len * 3): parameters_ws.column_dimensions[format_cell.get_column_letter( i)].width = 15.0 # Img img = Image("excelexporters/myems.png") parameters_ws.add_image(img, 'A1') # Title parameters_ws['B3'].alignment = b_r_alignment parameters_ws['B3'] = 'Name:' parameters_ws['C3'].border = b_border parameters_ws['C3'].alignment = b_c_alignment parameters_ws['C3'] = name parameters_ws['D3'].alignment = b_r_alignment parameters_ws['D3'] = 'Period:' parameters_ws['E3'].border = b_border parameters_ws['E3'].alignment = b_c_alignment parameters_ws['E3'] = period_type parameters_ws['B4'].alignment = b_r_alignment parameters_ws['B4'] = 'Reporting Start Datetime:' parameters_ws['C4'].border = b_border parameters_ws['C4'].alignment = b_c_alignment parameters_ws['C4'] = reporting_start_datetime_local parameters_ws['D4'].alignment = b_r_alignment parameters_ws['D4'] = 'Reporting End Datetime:' parameters_ws['E4'].border = b_border parameters_ws['E4'].alignment = b_c_alignment parameters_ws['E4'] = reporting_end_datetime_local parameters_ws_current_row_number = 6 parameters_ws['B' + str(parameters_ws_current_row_number)].font = title_font parameters_ws[ 'B' + str(parameters_ws_current_row_number)] = name + ' ' + 'Parameters' parameters_ws_current_row_number += 1 parameters_table_start_row_number = parameters_ws_current_row_number parameters_ws.row_dimensions[ parameters_ws_current_row_number].height = 80 parameters_ws_current_row_number += 1 table_current_col_number = 2 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border parameters_ws[col + str(parameters_ws_current_row_number - 1)].font = name_font parameters_ws[col + str(parameters_ws_current_row_number - 1)].alignment = c_c_alignment parameters_ws[col + str(parameters_ws_current_row_number - 1)] = parameters_data['names'][i] table_current_row_number = parameters_ws_current_row_number for j, value in enumerate(list(parameters_data['timestamps'][i])): col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = value col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = round( parameters_data['values'][i][j], 2) table_current_row_number += 1 table_current_col_number = table_current_col_number + 3 ################################################################################################################ # parameters chart and parameters table ################################################################################################################ ws['B' + str(current_sheet_parameters_row_number)].font = title_font ws['B' + str( current_sheet_parameters_row_number)] = name + ' ' + 'Parameters' current_sheet_parameters_row_number += 1 chart_start_row_number = current_sheet_parameters_row_number col_index = 0 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue line = LineChart() data_col = 3 + col_index * 3 labels_col = 2 + col_index * 3 col_index += 1 line.title = 'Parameters - ' + \ parameters_ws.cell(row=parameters_table_start_row_number, column=data_col).value labels = Reference(parameters_ws, min_col=labels_col, min_row=parameters_table_start_row_number + 1, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line_data = Reference( parameters_ws, min_col=data_col, min_row=parameters_table_start_row_number, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = False line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number) chart_start_row_number += 6 ws.add_chart(line, chart_cell) current_sheet_parameters_row_number = chart_start_row_number current_sheet_parameters_row_number += 1 filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active # Row height ws.row_dimensions[1].height = 102 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 42 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('L')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Constantia', size=15, bold=True) title_font = Font(name='宋体', size=15, bold=True) data_font = Font(name='Franklin Gothic Book', size=11) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000')) b_border = Border(bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_r_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") img.width = img.width * 0.85 img.height = img.height * 0.85 # img = Image("myems.png") ws.add_image(img, 'B1') # Title ws.row_dimensions[3].height = 60 ws['B3'].font = name_font ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'].font = name_font ws['C3'] = name ws['D3'].font = name_font ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'].font = name_font ws['E3'] = period_type ws['F3'].font = name_font ws['F3'].alignment = b_r_alignment ws['F3'] = 'Date:' ws['G3'].border = b_border ws['G3'].alignment = b_c_alignment ws['G3'].font = name_font ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local ws.merge_cells("G3:H3") if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename ################################## current_row_number = 6 reporting_period_data = report['reporting_period'] has_names_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_names_data_flag = False if has_names_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 报告期消耗' current_row_number += 1 category = reporting_period_data['names'] ca_len = len(category) ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].border = f_border col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = \ reporting_period_data['names'][i] + " " + reporting_period_data['energy_category_names'][i] + \ " (" + reporting_period_data['units'][i] + ")" col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '消耗' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '单位面积值' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round( reporting_period_data['subtotals_per_unit_area'][i], 2) col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '环比' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = str( round(reporting_period_data['increment_rates'][i] * 100, 2)) + '%' \ if reporting_period_data['increment_rates'][i] is not None else '-' col = chr(ord(col) + 1) current_row_number += 2 category_dict = group_by_category( reporting_period_data['energy_category_names']) for category_dict_name, category_dict_values in category_dict.items(): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = \ name + ' ' + category_dict_name + ' (' + reporting_period_data['units'][category_dict_values[0]] + \ ') 分项消耗占比' current_row_number += 1 table_start_row_number = current_row_number ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = '消耗' current_row_number += 1 for i in category_dict_values: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 3) current_row_number += 1 table_end_row_number = current_row_number - 1 pie = PieChart() pie.title = \ name + ' ' + category_dict_name + ' (' + reporting_period_data['units'][category_dict_values[0]] + \ ') 分项消耗占比' labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 6.6 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True ws.add_chart(pie, 'D' + str(table_start_row_number)) if len(category_dict_values) < 4: current_row_number = current_row_number - len( category_dict_values) + 4 current_row_number += 1 ####################### has_values_data = True has_timestamps_data = True if 'values' not in reporting_period_data.keys() or \ reporting_period_data['values'] is None or \ len(reporting_period_data['values']) == 0: has_values_data = False if 'timestamps' not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0 or \ len(reporting_period_data['timestamps'][0]) == 0: has_timestamps_data = False if has_values_data and has_timestamps_data: ca_len = len(reporting_period_data['names']) time = reporting_period_data['timestamps'][0] ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 详细数据' current_row_number += 1 chart_start_row_number = current_row_number current_row_number += ca_len * 6 table_start_row_number = current_row_number ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '日期时间' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" col = chr(ord(col) + 1) current_row_number += 1 for i in range(0, len(time)): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = time[i] col = 'C' for j in range(0, ca_len): ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['values'][j][i], 2) \ if reporting_period_data['values'][j][i] is not None else 0.00 col = chr(ord(col) + 1) current_row_number += 1 table_end_row_number = current_row_number - 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '小计' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) col = chr(ord(col) + 1) current_row_number += 2 format_time_width_number = 1.0 min_len_number = 1.0 min_width_number = 11.0 # format_time_width_number * min_len_number + 4 and min_width_number > 11.0 if period_type == 'hourly': format_time_width_number = 4.0 min_len_number = 2 min_width_number = 12.0 elif period_type == 'daily': format_time_width_number = 2.5 min_len_number = 4 min_width_number = 14.0 elif period_type == 'monthly': format_time_width_number = 2.1 min_len_number = 4 min_width_number = 12.4 elif period_type == 'yearly': format_time_width_number = 1.5 min_len_number = 5 min_width_number = 11.5 for i in range(0, ca_len): line = LineChart() line.title = '报告期消耗 - ' + \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) line_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = format_time_width_number * len(time) if len( time) > min_len_number else min_width_number if line.width > 24: line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = True line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number) chart_start_row_number += 6 ws.add_chart(line, chart_cell) filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active # Row height ws.row_dimensions[1].height = 102 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 42 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('L')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Constantia', size=15, bold=True) title_font = Font(name='宋体', size=15, bold=True) data_font = Font(name='Franklin Gothic Book', size=11) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000')) b_border = Border(bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_r_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") img.width = img.width * 0.85 img.height = img.height * 0.85 # img = Image("myems.png") ws.add_image(img, 'B1') # Title ws.row_dimensions[3].height = 60 ws['B3'].font = name_font ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'].font = name_font ws['C3'] = name ws['D3'].font = name_font ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'].font = name_font ws['E3'] = period_type ws['F3'].font = name_font ws['F3'].alignment = b_r_alignment ws['F3'] = 'Date:' ws['G3'].border = b_border ws['G3'].alignment = b_c_alignment ws['G3'].font = name_font ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local ws.merge_cells("G3:H3") if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename ################################## reporting_period_data = report['reporting_period'] has_cost_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_cost_data_flag = False if has_cost_data_flag: ws['B5'].font = title_font ws['B5'] = name + ' 报告期收入' category = reporting_period_data['names'] ca_len = len(category) ws.row_dimensions[7].height = 60 ws['B6'].fill = table_fill ws['B6'].border = f_border ws['B7'].font = title_font ws['B7'].alignment = c_c_alignment ws['B7'] = '报告期收入' ws['B7'].border = f_border ws['B8'].font = title_font ws['B8'].alignment = c_c_alignment ws['B8'] = '环比' ws['B8'].border = f_border col = '' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + '6'].fill = table_fill ws[col + '6'].font = name_font ws[col + '6'].alignment = c_c_alignment ws[col + '6'] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + '6'].border = f_border ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = round(reporting_period_data['subtotals'][i], 2) ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \ if reporting_period_data['increment_rates'][i] is not None else "-" ws[col + '8'].border = f_border col = chr(ord(col) + 1) ws[col + '6'].fill = table_fill ws[col + '6'].font = name_font ws[col + '6'].alignment = c_c_alignment ws[col + '6'] = "总计 (" + reporting_period_data['total_unit'] + ")" ws[col + '6'].border = f_border ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = round(reporting_period_data['total'], 2) ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = str(round(reporting_period_data['total_increment_rate'] * 100, 2)) + "%" \ if reporting_period_data['total_increment_rate'] is not None else "-" ws[col + '8'].border = f_border else: for i in range(6, 8 + 1): ws.row_dimensions[i].height = 0.1 ################################## current_row_number = 10 has_subtotals_data_flag = True if "subtotals" not in reporting_period_data.keys() or \ reporting_period_data['subtotals'] is None or \ len(reporting_period_data['subtotals']) == 0: has_subtotals_data_flag = False if has_subtotals_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 收入占比' current_row_number += 1 table_start_row_number = current_row_number ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = name_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = '收入' ws['D' + str(current_row_number)].fill = table_fill ws['D' + str(current_row_number)].font = name_font ws['D' + str(current_row_number)].alignment = c_c_alignment ws['D' + str(current_row_number)].border = f_border ws['D' + str(current_row_number)] = '收入占比' current_row_number += 1 ca_len = len(reporting_period_data['names']) income_sum = Decimal(0.0) for i in range(0, ca_len): income_sum = round(reporting_period_data['subtotals'][i], 2) + income_sum for i in range(0, ca_len): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = reporting_period_data['names'][i] ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].font = title_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) ws['D' + str(current_row_number)].font = title_font ws['D' + str(current_row_number)].alignment = c_c_alignment ws['D' + str(current_row_number)].border = f_border ws['D' + str(current_row_number)] = '{:.2%}'.format(round( reporting_period_data['subtotals'][i], 2) / income_sum) \ if income_sum is not None and income_sum != Decimal(0.0) \ else '' current_row_number += 1 table_end_row_number = current_row_number - 1 pie = PieChart() pie.title = name + ' 收入占比' labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 6.6 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True table_cell = 'F' + str(table_start_row_number - 1) ws.add_chart(pie, table_cell) if ca_len < 4: current_row_number = current_row_number - ca_len + 4 else: for i in range(13, 22 + 1): ws.row_dimensions[i].height = 0.1 ############################################# current_row_number = 14 reporting_period_data = report['reporting_period'] times = reporting_period_data['timestamps'] has_detail_data_flag = True ca_len = len(report['reporting_period']['names']) real_timestamps_len = timestamps_data_not_equal_0( report['parameters']['timestamps']) table_row = (current_row_number + 1) + ca_len * 6 + real_timestamps_len * 7 if "timestamps" not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0: has_detail_data_flag = False if has_detail_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 详细数据' ws.row_dimensions[table_row].height = 60 ws['B' + str(table_row)].fill = table_fill ws['B' + str(table_row)].font = title_font ws['B' + str(table_row)].border = f_border ws['B' + str(table_row)].alignment = c_c_alignment ws['B' + str(table_row)] = '日期时间' time = times[0] has_data = False max_row = 0 if len(time) > 0: has_data = True max_row = table_row + len(time) if has_data: for i in range(0, len(time)): col = 'B' row = str(table_row + 1 + i) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = time[i] ws[col + row].border = f_border for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(table_row)].fill = table_fill ws[col + str(table_row)].font = title_font ws[col + str(table_row)].alignment = c_c_alignment ws[col + str(table_row)] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + str(table_row)].border = f_border # 39 data time = times[i] time_len = len(time) for j in range(0, time_len): row = str(table_row + 1 + j) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round( reporting_period_data['values'][i][j], 2) ws[col + row].border = f_border line = LineChart() line.title = \ '报告期收入 - ' + reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" labels = Reference(ws, min_col=2, min_row=table_row + 1, max_row=max_row) line_data = Reference(ws, min_col=3 + i, min_row=table_row, max_row=max_row) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = True line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(current_row_number + 1 + 6 * i) ws.add_chart(line, chart_cell) row = str(max_row + 1) ws['B' + row].font = title_font ws['B' + row].alignment = c_c_alignment ws['B' + row] = '小计' ws['B' + row].border = f_border col = '' for i in range(0, ca_len): col = chr(ord('C') + i) row = str(max_row + 1) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(reporting_period_data['subtotals'][i], 2) ws[col + row].border = f_border col = chr(ord(col) + 1) ws[col + str(table_row)].fill = table_fill ws[col + str(table_row)].font = title_font ws[col + str(table_row)].alignment = c_c_alignment ws[col + str(table_row )] = '总计 (' + report['reporting_period']['total_unit'] + ')' ws[col + str(table_row)].border = f_border total_sum = 0 for j in range(0, len(time)): row = str(table_row + 1 + j) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment every_day_sum = reporting_period_values_every_day_sum( reporting_period_data, j, ca_len) total_sum += every_day_sum ws[col + row] = round(every_day_sum, 2) ws[col + row].border = f_border row = str(table_row + 1 + len(time)) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(total_sum, 2) ws[col + row].border = f_border else: for i in range(37, 69 + 1): ws.row_dimensions[i].height = 0.1 ########################################## current_sheet_parameters_row_number = current_row_number + ca_len * 6 + 1 has_parameters_names_and_timestamps_and_values_data = True if 'parameters' not in report.keys() or \ report['parameters'] is None or \ 'names' not in report['parameters'].keys() or \ report['parameters']['names'] is None or \ len(report['parameters']['names']) == 0 or \ 'timestamps' not in report['parameters'].keys() or \ report['parameters']['timestamps'] is None or \ len(report['parameters']['timestamps']) == 0 or \ 'values' not in report['parameters'].keys() or \ report['parameters']['values'] is None or \ len(report['parameters']['values']) == 0 or \ timestamps_data_all_equal_0(report['parameters']['timestamps']): has_parameters_names_and_timestamps_and_values_data = False if has_parameters_names_and_timestamps_and_values_data: ############################### # new worksheet ############################### parameters_data = report['parameters'] parameters_names_len = len(parameters_data['names']) parameters_ws = wb.create_sheet('相关参数') parameters_timestamps_data_max_len = \ get_parameters_timestamps_lists_max_len(list(parameters_data['timestamps'])) # Row height parameters_ws.row_dimensions[1].height = 102 for i in range(2, 7 + 1): parameters_ws.row_dimensions[i].height = 42 for i in range(8, parameters_timestamps_data_max_len + 10): parameters_ws.row_dimensions[i].height = 60 # Col width parameters_ws.column_dimensions['A'].width = 1.5 parameters_ws.column_dimensions['B'].width = 25.0 for i in range(3, 12 + parameters_names_len * 3): parameters_ws.column_dimensions[format_cell.get_column_letter( i)].width = 15.0 # Img img = Image("excelexporters/myems.png") img.width = img.width * 0.85 img.height = img.height * 0.85 # img = Image("myems.png") parameters_ws.add_image(img, 'B1') # Title parameters_ws.row_dimensions[3].height = 60 parameters_ws['B3'].font = name_font parameters_ws['B3'].alignment = b_r_alignment parameters_ws['B3'] = 'Name:' parameters_ws['C3'].border = b_border parameters_ws['C3'].alignment = b_c_alignment parameters_ws['C3'].font = name_font parameters_ws['C3'] = name parameters_ws['D3'].font = name_font parameters_ws['D3'].alignment = b_r_alignment parameters_ws['D3'] = 'Period:' parameters_ws['E3'].border = b_border parameters_ws['E3'].alignment = b_c_alignment parameters_ws['E3'].font = name_font parameters_ws['E3'] = period_type parameters_ws['F3'].font = name_font parameters_ws['F3'].alignment = b_r_alignment parameters_ws['F3'] = 'Date:' parameters_ws['G3'].border = b_border parameters_ws['G3'].alignment = b_c_alignment parameters_ws['G3'].font = name_font parameters_ws[ 'G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local parameters_ws.merge_cells("G3:H3") parameters_ws_current_row_number = 6 parameters_ws['B' + str(parameters_ws_current_row_number)].font = title_font parameters_ws['B' + str(parameters_ws_current_row_number)] = name + ' 相关参数' parameters_ws_current_row_number += 1 parameters_table_start_row_number = parameters_ws_current_row_number parameters_ws.row_dimensions[ parameters_ws_current_row_number].height = 80 parameters_ws_current_row_number += 1 table_current_col_number = 'B' for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue parameters_ws[table_current_col_number + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[table_current_col_number + str(parameters_ws_current_row_number - 1)].border = f_border col = chr(ord(table_current_col_number) + 1) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border parameters_ws[col + str(parameters_ws_current_row_number - 1)].font = name_font parameters_ws[col + str(parameters_ws_current_row_number - 1)].alignment = c_c_alignment parameters_ws[col + str(parameters_ws_current_row_number - 1)] = parameters_data['names'][i] table_current_row_number = parameters_ws_current_row_number for j, value in enumerate(list(parameters_data['timestamps'][i])): col = table_current_col_number parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = value col = chr(ord(col) + 1) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = round( parameters_data['values'][i][j], 2) table_current_row_number += 1 table_current_col_number = chr(ord(table_current_col_number) + 3) ######################################################## # parameters chart and parameters table ######################################################## ws['B' + str(current_sheet_parameters_row_number)].font = title_font ws['B' + str(current_sheet_parameters_row_number)] = name + ' 相关参数' current_sheet_parameters_row_number += 1 chart_start_row_number = current_sheet_parameters_row_number col_index = 0 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue line = LineChart() data_col = 3 + col_index * 3 labels_col = 2 + col_index * 3 col_index += 1 line.title = '相关参数 - ' + \ parameters_ws.cell(row=parameters_table_start_row_number, column=data_col).value labels = Reference(parameters_ws, min_col=labels_col, min_row=parameters_table_start_row_number + 1, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line_data = Reference( parameters_ws, min_col=data_col, min_row=parameters_table_start_row_number, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = False line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number) chart_start_row_number += 6 ws.add_chart(line, chart_cell) current_sheet_parameters_row_number = chart_start_row_number current_sheet_parameters_row_number += 1 ########################################## filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active # Row height ws.row_dimensions[1].height = 102 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 42 # for i in range(2, 37 + 1): # ws.row_dimensions[i].height = 30 # # for i in range(38, 69 + 1): # ws.row_dimensions[i].height = 30 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('L')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Constantia', size=15, bold=True) title_font = Font(name='宋体', size=15, bold=True) data_font = Font(name='Franklin Gothic Book', size=11) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000')) b_border = Border(bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_r_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") img.width = img.width * 0.85 img.height = img.height * 0.85 # img = Image("myems.png") ws.add_image(img, 'B1') # Title ws.row_dimensions[3].height = 60 ws['B3'].font = name_font ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'].font = name_font ws['C3'] = name ws['D3'].font = name_font ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'].font = name_font ws['E3'] = period_type ws['F3'].font = name_font ws['F3'].alignment = b_r_alignment ws['F3'] = 'Date:' ws['G3'].border = b_border ws['G3'].alignment = b_c_alignment ws['G3'].font = name_font ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local ws.merge_cells("G3:H3") if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename ################################## reporting_period_data = report['reporting_period'] has_cost_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_cost_data_flag = False if has_cost_data_flag: ws['B6'].font = title_font ws['B6'] = name + ' 报告期成本' category = reporting_period_data['names'] ca_len = len(category) ws.row_dimensions[7].height = 60 ws['B7'].fill = table_fill ws['B7'].border = f_border ws['B8'].font = title_font ws['B8'].alignment = c_c_alignment ws['B8'] = '成本' ws['B8'].border = f_border ws['B9'].font = title_font ws['B9'].alignment = c_c_alignment ws['B9'] = '单位面积值' ws['B9'].border = f_border ws['B10'].font = title_font ws['B10'].alignment = c_c_alignment ws['B10'] = '环比' ws['B10'].border = f_border col = '' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + '7'].fill = table_fill ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = round(reporting_period_data['subtotals'][i], 2) ws[col + '8'].border = f_border ws[col + '9'].font = name_font ws[col + '9'].alignment = c_c_alignment ws[col + '9'] = round( reporting_period_data['subtotals_per_unit_area'][i], 2) ws[col + '9'].border = f_border ws[col + '10'].font = name_font ws[col + '10'].alignment = c_c_alignment ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \ if reporting_period_data['increment_rates'][i] is not None else "-" ws[col + '10'].border = f_border col = chr(ord(col) + 1) ws[col + '7'].fill = table_fill ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = "总计 (" + reporting_period_data['total_unit'] + ")" ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = round(reporting_period_data['total'], 2) ws[col + '8'].border = f_border ws[col + '9'].font = name_font ws[col + '9'].alignment = c_c_alignment ws[col + '9'] = round(reporting_period_data['total_per_unit_area'], 2) ws[col + '9'].border = f_border ws[col + '10'].font = name_font ws[col + '10'].alignment = c_c_alignment ws[col + '10'] = str(round(reporting_period_data['total_increment_rate'] * 100, 2)) + "%" \ if reporting_period_data['total_increment_rate'] is not None else "-" ws[col + '10'].border = f_border else: for i in range(6, 10 + 1): ws.row_dimensions[i].height = 0.1 ############################## has_ele_peak_flag = True if "toppeaks" not in reporting_period_data.keys() or \ reporting_period_data['toppeaks'] is None or \ len(reporting_period_data['toppeaks']) == 0: has_ele_peak_flag = False if has_ele_peak_flag: ws['B12'].font = title_font ws['B12'] = name + '分时用电成本' ws.row_dimensions[13].height = 60 ws['B13'].fill = table_fill ws['B13'].font = name_font ws['B13'].alignment = c_c_alignment ws['B13'].border = f_border ws['C13'].fill = table_fill ws['C13'].font = name_font ws['C13'].alignment = c_c_alignment ws['C13'].border = f_border ws['C13'] = '分时用电成本' ws['B14'].font = title_font ws['B14'].alignment = c_c_alignment ws['B14'] = '尖' ws['B14'].border = f_border ws['C14'].font = title_font ws['C14'].alignment = c_c_alignment ws['C14'].border = f_border ws['C14'] = round(reporting_period_data['toppeaks'][0], 2) ws['B15'].font = title_font ws['B15'].alignment = c_c_alignment ws['B15'] = '峰' ws['B15'].border = f_border ws['C15'].font = title_font ws['C15'].alignment = c_c_alignment ws['C15'].border = f_border ws['C15'] = round(reporting_period_data['onpeaks'][0], 2) ws['B16'].font = title_font ws['B16'].alignment = c_c_alignment ws['B16'] = '平' ws['B16'].border = f_border ws['C16'].font = title_font ws['C16'].alignment = c_c_alignment ws['C16'].border = f_border ws['C16'] = round(reporting_period_data['midpeaks'][0], 2) ws['B17'].font = title_font ws['B17'].alignment = c_c_alignment ws['B17'] = '谷' ws['B17'].border = f_border ws['C17'].font = title_font ws['C17'].alignment = c_c_alignment ws['C17'].border = f_border ws['C17'] = round(reporting_period_data['offpeaks'][0], 2) pie = PieChart() pie.title = name + '分时用电成本' labels = Reference(ws, min_col=2, min_row=14, max_row=17) pie_data = Reference(ws, min_col=3, min_row=13, max_row=17) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 7.25 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True ws.add_chart(pie, "D13") else: for i in range(12, 18 + 1): ws.row_dimensions[i].height = 0.1 ################################## current_row_number = 19 has_child_flag = True if "child_space" not in report.keys() or "energy_category_names" not in report['child_space'].keys() or \ len(report['child_space']["energy_category_names"]) == 0 \ or 'child_space_names_array' not in report['child_space'].keys() \ or report['child_space']['energy_category_names'] is None \ or len(report['child_space']['child_space_names_array']) == 0 \ or len(report['child_space']['child_space_names_array'][0]) == 0: has_child_flag = False if has_child_flag: child = report['child_space'] ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 子空间数据' current_row_number += 1 table_start_row_number = current_row_number ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].border = f_border ca_len = len(child['energy_category_names']) col = '' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = child['energy_category_names'][ i] + ' (' + child['units'][i] + ')' col = chr(ord(col) + 1) ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number )] = '总计 (' + report['reporting_period']['total_unit'] + ')' space_len = len(child['child_space_names_array'][0]) for i in range(0, space_len): current_row_number += 1 row = str(current_row_number) ws['B' + row].font = name_font ws['B' + row].alignment = c_c_alignment ws['B' + row] = child['child_space_names_array'][0][i] ws['B' + row].border = f_border col = '' every_day_sum = 0 for j in range(0, ca_len): col = chr(ord('C') + j) ws[col + row].font = name_font ws[col + row].alignment = c_c_alignment every_day_sum += child['subtotals_array'][j][i] ws[col + row] = round(child['subtotals_array'][j][i], 2) ws[col + row].border = f_border col = chr(ord(col) + 1) ws[col + row].font = name_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(every_day_sum, 2) ws[col + row].border = f_border table_end_row_number = current_row_number current_row_number += 1 chart_start_row_number = current_row_number # Pie for i in range(0, ca_len): pie = PieChart() labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 6.6 pie.width = 8 pie.title = ws.cell(column=3 + i, row=table_start_row_number).value s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True chart_cell = '' if i % 2 == 0: chart_cell = 'B' + str(chart_start_row_number) else: chart_cell = 'E' + str(chart_start_row_number) chart_start_row_number += 5 ws.add_chart(pie, chart_cell) # chart_col = chr(ord('B') + 2 * i) # chart_cell = chart_col + str(current_row_number) # ws.add_chart(pie, chart_cell) current_row_number = chart_start_row_number if ca_len % 2 == 1: current_row_number += 5 # else: # for i in range(19, 36 + 1): # current_row_number = 36 # ws.row_dimensions[i].height = 0.1 current_row_number += 1 ############################################# reporting_period_data = report['reporting_period'] times = reporting_period_data['timestamps'] has_detail_data_flag = True ca_len = len(report['reporting_period']['names']) table_row = (current_row_number + 1) + ca_len * 6 if "timestamps" not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0: has_detail_data_flag = False if has_detail_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 详细数据' ws.row_dimensions[table_row].height = 60 ws['B' + str(table_row)].fill = table_fill ws['B' + str(table_row)].font = title_font ws['B' + str(table_row)].border = f_border ws['B' + str(table_row)].alignment = c_c_alignment ws['B' + str(table_row)] = '日期时间' time = times[0] has_data = False max_row = 0 if len(time) > 0: has_data = True max_row = table_row + len(time) if has_data: for i in range(0, len(time)): col = 'B' row = str(table_row + 1 + i) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = time[i] ws[col + row].border = f_border for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(table_row)].fill = table_fill ws[col + str(table_row)].font = title_font ws[col + str(table_row)].alignment = c_c_alignment ws[col + str(table_row)] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + str(table_row)].border = f_border # 39 data time = times[i] time_len = len(time) for j in range(0, time_len): row = str(table_row + 1 + j) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round( reporting_period_data['values'][i][j], 2) ws[col + row].border = f_border line = LineChart() line.title = \ '报告期成本 - ' + reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" labels = Reference(ws, min_col=2, min_row=table_row + 1, max_row=max_row) line_data = Reference(ws, min_col=3 + i, min_row=table_row, max_row=max_row) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = True line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(current_row_number + 1 + 6 * i) ws.add_chart(line, chart_cell) row = str(max_row + 1) ws['B' + row].font = title_font ws['B' + row].alignment = c_c_alignment ws['B' + row] = '小计' ws['B' + row].border = f_border col = '' for i in range(0, ca_len): col = chr(ord('C') + i) row = str(max_row + 1) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(reporting_period_data['subtotals'][i], 2) ws[col + row].border = f_border col = chr(ord(col) + 1) ws[col + str(table_row)].fill = table_fill ws[col + str(table_row)].font = title_font ws[col + str(table_row)].alignment = c_c_alignment ws[col + str(table_row )] = '总计 (' + report['reporting_period']['total_unit'] + ')' ws[col + str(table_row)].border = f_border total_sum = 0 for j in range(0, len(time)): row = str(table_row + 1 + j) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment every_day_sum = reporting_period_values_every_day_sum( reporting_period_data, j, ca_len) total_sum += every_day_sum ws[col + row] = round(every_day_sum, 2) ws[col + row].border = f_border row = str(table_row + 1 + len(time)) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(total_sum, 2) ws[col + row].border = f_border else: for i in range(37, 69 + 1): ws.row_dimensions[i].height = 0.1 filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def writeresult(result, pathsave): result = sortresult(result) statuscount = { "ok": 0, "wildcard": 0, "expire": 0, "expiresoon": 0, "expiresoon": 0, "validitytoolong": 0, "notmatch": 0, "timeout": 0, "errresolution": 0, "error": 0 } wb = Workbook() wssommaire = wb.active wssommaire.title = u'Sommaire' wssommaire.column_dimensions['A'].width = len("VALIDITE TROP LONGUE") * 1.3 wssommaire["A1"] = u"EXPIRÉ" wssommaire["A1"].fill = PatternFill(fill_type="solid", start_color=getstatuscolor("expire"), end_color=getstatuscolor("expire")) wssommaire["A1"].font = Font(color='FFFFFF') wssommaire["A2"] = u"EXPIRE BIENTÔT" wssommaire["A2"].fill = PatternFill( fill_type="solid", start_color=getstatuscolor("expiresoon"), end_color=getstatuscolor("expiresoon")) wssommaire["A2"].font = Font(color='FFFFFF') wssommaire["A3"] = "VALIDITE TROP LONGUE" wssommaire["A3"].fill = PatternFill( fill_type="solid", start_color=getstatuscolor("validitytoolong"), end_color=getstatuscolor("validitytoolong")) wssommaire["A3"].font = Font(color='000000') wssommaire["A4"] = u"NOM D'HÔTE INVALIDE" wssommaire["A4"].fill = PatternFill(fill_type="solid", start_color=getstatuscolor("notmatch"), end_color=getstatuscolor("notmatch")) wssommaire["A4"].font = Font(color='000000') wssommaire["A5"] = "WILDCARD" wssommaire["A5"].fill = PatternFill(fill_type="solid", start_color=getstatuscolor("wildcard"), end_color=getstatuscolor("wildcard")) wssommaire["A5"].font = Font(color='FFFFFF') wssommaire["A6"] = "VALIDES" wssommaire["A6"].fill = PatternFill(fill_type="solid", start_color=getstatuscolor("ok"), end_color=getstatuscolor("ok")) wssommaire["A6"].font = Font(color='FFFFFF') ws = wb.create_sheet(u'Détails') listwidthcolumn = [] ws['A1'] = "Status certificat" ws['A1'].alignment = Alignment(horizontal='center') ws['A1'].font = Font(bold=True) ws.column_dimensions['A'].width = len("Status certificat") * 1.3 ws['B1'] = "Domaines" ws['B1'].alignment = Alignment(horizontal='center') ws['B1'].font = Font(bold=True) ws['C1'] = "Port" ws.column_dimensions['C'].width = len("Port") * 1.3 ws['C1'].alignment = Alignment(horizontal='center') ws['C1'].font = Font(bold=True) ws['D1'] = "Date de délivrance" ws.column_dimensions['D'].width = len("Date de délivrance") * 1.3 ws['D1'].alignment = Alignment(horizontal='center') ws['D1'].font = Font(bold=True) ws['E1'] = "Date d'expiration" ws.column_dimensions['E'].width = len("Date d'expiration") * 1.3 ws['E1'].alignment = Alignment(horizontal='center') ws['E1'].font = Font(bold=True) ws['F1'] = "Jours restants" ws.column_dimensions['F'].width = len("Jours restants") * 1.3 ws['F1'].alignment = Alignment(horizontal='center') ws['F1'].font = Font(bold=True) ws['G1'] = "Validité (nombre de jours)" ws.column_dimensions['G'].width = len("Validité (nombre de jours)") * 1.3 ws['G1'].alignment = Alignment(horizontal='center') ws['G1'].font = Font(bold=True) ws['H1'] = "Vérifié par" ws.column_dimensions['H'].width = len("Emis par") * 1.3 ws['H1'].alignment = Alignment(horizontal='center') ws['H1'].font = Font(bold=True) ws['I1'] = "Emis pour" ws.column_dimensions['I'].width = len("Emis pour") * 1.3 ws['I1'].alignment = Alignment(horizontal='center') ws['I1'].font = Font(bold=True) ws['J1'] = "Numéro de série" ws.column_dimensions['J'].width = len("Numéro de série") * 1.3 ws['J1'].alignment = Alignment(horizontal='center') ws['J1'].font = Font(bold=True) currentline = 2 wsnotmatch = wb.create_sheet(u'Noms d\'hôte invalides') wsnotmatch['A1'] = "Domaines" wsnotmatch['B1'] = "Port" wserrresolution = wb.create_sheet(u'Erreur de résolution') wserrresolution['A1'] = "Domaines" wserrresolution['B1'] = "Port" wstimeout = wb.create_sheet(u'Timeout') wstimeout['A1'] = "Domaines" wstimeout['B1'] = "Port" wsinvalidecert = wb.create_sheet(u'Certificats invalides') wsinvalidecert['A1'] = "Domaines" wsinvalidecert['B1'] = "Port" wserror = wb.create_sheet(u'Autres erreurs') wserror['A1'] = "Domaines" wserror['B1'] = "Port" countersheet = { 'principal': 1, 'notmatch': 1, 'errresolution': 1, 'timeout': 1, 'error': 1 } currentlinenotmatch = 1 currentsheetinfo = {'object': None, 'line': 0} for current in result: if current["status"] == "ok": statuscount["ok"] += 1 countersheet["principal"] += 1 ws['A' + str(countersheet["principal"])] = "VALIDE" ws['A' + str(countersheet["principal"])].fill = PatternFill( fill_type="solid", start_color=getstatuscolor("ok"), end_color=getstatuscolor("ok")) currentsheetinfo['object'] = ws currentsheetinfo['line'] = countersheet["principal"] elif current["status"] == "wildcard": statuscount["wildcard"] += 1 countersheet["principal"] += 1 ws['A' + str(countersheet["principal"])] = "WILDCARD" ws['A' + str(countersheet["principal"])].fill = PatternFill( fill_type="solid", start_color=getstatuscolor("wildcard"), end_color=getstatuscolor("wildcard")) currentsheetinfo['object'] = ws currentsheetinfo['line'] = countersheet["principal"] elif current["status"] == "expire": statuscount["expire"] += 1 countersheet["principal"] += 1 ws['A' + str(countersheet["principal"])] = "EXPIRÉ" ws['A' + str(countersheet["principal"])].fill = PatternFill( fill_type="solid", start_color=getstatuscolor("expire"), end_color=getstatuscolor("expire")) currentsheetinfo['object'] = ws currentsheetinfo['line'] = countersheet["principal"] elif current["status"] == "expiresoon": statuscount["expiresoon"] += 1 countersheet["principal"] += 1 ws['A' + str(countersheet["principal"])] = "EXPIRE BIENTOT" ws['A' + str(countersheet["principal"])].fill = PatternFill( fill_type="solid", start_color=getstatuscolor("expiresoon"), end_color=getstatuscolor("expiresoon")) currentsheetinfo['object'] = ws currentsheetinfo['line'] = countersheet["principal"] elif current["status"] == "validitytoolong": statuscount["validitytoolong"] += 1 countersheet["principal"] += 1 if ws.column_dimensions['A'].width < len( "VALIDITE TROP LONGUE") * 1.3: ws.column_dimensions['A'].width = len( "VALIDITE TROP LONGUE") * 1.3 ws['A' + str(countersheet["principal"])] = "VALIDITÉ TROP LONGUE" ws['A' + str(countersheet["principal"])].fill = PatternFill( fill_type="solid", start_color=getstatuscolor("validitytoolong"), end_color=getstatuscolor("validitytoolong")) currentsheetinfo['object'] = ws currentsheetinfo['line'] = countersheet["principal"] elif current["status"] == "notmatch": statuscount["notmatch"] += 1 countersheet["notmatch"] += 1 if wsnotmatch.column_dimensions['A'].width < len( "HOSTNAME INVALIDE") * 1.3: wsnotmatch.column_dimensions['A'].width = len( "HOSTNAME INVALIDE") * 1.3 currentsheetinfo['object'] = wsnotmatch currentsheetinfo['line'] = countersheet["notmatch"] else: if current["status"] == "errresolution": countersheet["errresolution"] += 1 currentsheetinfo['object'] = wserrresolution currentsheetinfo['line'] = countersheet["errresolution"] statuscount["errresolution"] += 1 elif current["status"] == "timeout": countersheet["timeout"] += 1 statuscount["timeout"] += 1 currentsheetinfo['line'] = countersheet["timeout"] currentsheetinfo['object'] = wstimeout else: countersheet["error"] += 1 statuscount["error"] += 1 currentsheetinfo['line'] = countersheet["error"] currentsheetinfo['object'] = wserror if currentsheetinfo['object'] == ws: ws['A' + str(countersheet["principal"])] = getstatustext( current["status"]) ws['A' + str(countersheet["principal"])].fill = PatternFill( fill_type="solid", start_color=getstatuscolor(current["status"]), end_color=getstatuscolor(current["status"])) ws['A' + str(countersheet["principal"])].font = Font( color=getstatustextcolor(current["status"])) ws['A' + str(countersheet["principal"])].alignment = Alignment( horizontal='center') ws['B' + str(countersheet["principal"])] = current["domain"] if ws.column_dimensions['B'].width < len( current["domain"] ) * 1.3 and ws.column_dimensions['B'].width != 255: if len(current["domain"]) * 1.3 >= 255: ws.column_dimensions['B'].width = 255 else: ws.column_dimensions['B'].width = len( current["domain"]) * 1.3 if current["status"] == "errresolution": ws['C' + str(countersheet["principal"])] = '*' else: ws['C' + str(countersheet["principal"])] = current["port"] if ws.column_dimensions['C'].width < len(current["port"]) * 1.3: ws.column_dimensions['C'].width = len(current["port"]) * 1.3 if (str(current["notBefore"]) != "error"): ws['D' + str(countersheet["principal"])] = str( current["notBefore"].year) + '-' + "{:02d}".format( current["notBefore"].month) + '-' + "{:02d}".format( current["notBefore"].day) else: ws['D' + str(countersheet["principal"])] = "ERROR" if (str(current["notAfter"]) != "error"): ws['E' + str(countersheet["principal"])] = str( current["notAfter"].year) + '-' + "{:02d}".format( current["notAfter"].month) + '-' + "{:02d}".format( current["notAfter"].day) else: ws['E' + str(countersheet["principal"])] = "ERROR" if (str(current["serialNumber"]) != "error"): if ws.column_dimensions['J'].width < len( str(current["serialNumber"])) * 1.3: ws.column_dimensions['J'].width = len( str(current["serialNumber"])) * 1.3 ws['J' + str(countersheet["principal"])] = str( current["serialNumber"]) else: ws['J' + str(countersheet["principal"])] = "ERROR" ws['F' + str(countersheet["principal"])] = str( current["deltaToday"]) ws['G' + str(countersheet["principal"])] = str( current["periodevalidity"]) ws['H' + str(countersheet["principal"])] = current["deliver"] if ws.column_dimensions['H'].width < len(current["deliver"]) * 1.3: ws.column_dimensions['H'].width = len(current["deliver"]) * 1.3 ws['I' + str(countersheet["principal"])] = current["deliverfor"] if ws.column_dimensions['I'].width < len( current["deliverfor"]) * 1.3: ws.column_dimensions['I'].width = len( current["deliverfor"]) * 1.3 else: currentsheetinfo['object'][ 'A' + str(currentsheetinfo['line'])] = current["domain"] currentsheetinfo['object'][ 'B' + str(currentsheetinfo['line'])] = current["port"] wssommaire["B1"] = statuscount["expire"] wssommaire["B2"] = statuscount["expiresoon"] wssommaire["B3"] = statuscount["validitytoolong"] wssommaire["B4"] = statuscount["notmatch"] wssommaire["B5"] = statuscount["wildcard"] wssommaire["B6"] = statuscount["ok"] pie = PieChart() labels = Reference(wssommaire, min_col=1, min_row=1, max_col=1, max_row=6) data = Reference(wssommaire, min_col=2, min_row=1, max_row=6, max_col=2) series = Series(data, title="Vue sommaire des certificats SSL") pie.append(series) pie.height = 11 pie.width = 14 pie.set_categories(labels) pie.dataLabels = label.DataLabelList() pie.dataLabels.showPercent = True pie.title = "Vue sommaire des certificats SSL" wssommaire.add_chart(pie, "D4") wb.save(pathsave + 'StatusCertificates.xlsx')
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active ws.title = "CombinedEquipmentIncome" # Row height ws.row_dimensions[1].height = 102 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 42 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('L')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Arial', size=15, bold=True) title_font = Font(name='Arial', size=15, bold=True) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000')) b_border = Border(bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") ws.add_image(img, 'A1') # Title ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'] = name ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'] = period_type ws['B4'].alignment = b_r_alignment ws['B4'] = 'Reporting Start Datetime:' ws['C4'].border = b_border ws['C4'].alignment = b_c_alignment ws['C4'] = reporting_start_datetime_local ws['D4'].alignment = b_r_alignment ws['D4'] = 'Reporting End Datetime:' ws['E4'].border = b_border ws['E4'].alignment = b_c_alignment ws['E4'] = reporting_end_datetime_local if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename #################################################################################################################### reporting_period_data = report['reporting_period'] has_cost_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_cost_data_flag = False if has_cost_data_flag: ws['B5'].font = title_font ws['B5'] = name + ' ' + 'Reporting Period Income' category = reporting_period_data['names'] ca_len = len(category) ws.row_dimensions[7].height = 60 ws['B6'].fill = table_fill ws['B6'].border = f_border ws['B7'].font = title_font ws['B7'].alignment = c_c_alignment ws['B7'] = 'Reporting Period Income' ws['B7'].border = f_border ws['B8'].font = title_font ws['B8'].alignment = c_c_alignment ws['B8'] = 'Increment Rate' ws['B8'].border = f_border col = '' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + '6'].fill = table_fill ws[col + '6'].font = name_font ws[col + '6'].alignment = c_c_alignment ws[col + '6'] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + '6'].border = f_border ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = round(reporting_period_data['subtotals'][i], 2) ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \ if reporting_period_data['increment_rates'][i] is not None else "-" ws[col + '8'].border = f_border col = chr(ord(col) + 1) ws[col + '6'].fill = table_fill ws[col + '6'].font = name_font ws[col + '6'].alignment = c_c_alignment ws[col + '6'] = "Total (" + reporting_period_data['total_unit'] + ")" ws[col + '6'].border = f_border ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = round(reporting_period_data['total'], 2) ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = str(round(reporting_period_data['total_increment_rate'] * 100, 2)) + "%" \ if reporting_period_data['total_increment_rate'] is not None else "-" ws[col + '8'].border = f_border else: for i in range(6, 8 + 1): ws.row_dimensions[i].height = 0.1 #################################################################################################################### current_row_number = 10 has_subtotals_data_flag = True if "subtotals" not in reporting_period_data.keys() or \ reporting_period_data['subtotals'] is None or \ len(reporting_period_data['subtotals']) == 0: has_subtotals_data_flag = False if has_subtotals_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + 'Incomes by Energy Category' current_row_number += 1 table_start_row_number = current_row_number ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = name_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = 'Incomes' ws['D' + str(current_row_number)].fill = table_fill ws['D' + str(current_row_number)].font = name_font ws['D' + str(current_row_number)].alignment = c_c_alignment ws['D' + str(current_row_number)].border = f_border ws['D' + str(current_row_number)] = 'Proportion' current_row_number += 1 ca_len = len(reporting_period_data['names']) income_sum = Decimal(0.0) for i in range(0, ca_len): income_sum = round(reporting_period_data['subtotals'][i], 2) + income_sum for i in range(0, ca_len): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = reporting_period_data['names'][i] ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].font = title_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) ws['D' + str(current_row_number)].font = title_font ws['D' + str(current_row_number)].alignment = c_c_alignment ws['D' + str(current_row_number)].border = f_border ws['D' + str(current_row_number)] = '{:.2%}'.format(round( reporting_period_data['subtotals'][i], 2) / income_sum) if income_sum is not None and \ income_sum != Decimal(0.0) else " " current_row_number += 1 table_end_row_number = current_row_number - 1 pie = PieChart() pie.title = name + ' ' + 'Incomes by Energy Category' labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 6.6 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True table_cell = 'F' + str(table_start_row_number - 1) ws.add_chart(pie, table_cell) if ca_len < 4: current_row_number = current_row_number - ca_len + 4 else: for i in range(13, 22 + 1): ws.row_dimensions[i].height = 0.1 #################################################################################################################### current_row_number = 14 reporting_period_data = report['reporting_period'] times = reporting_period_data['timestamps'] has_detail_data_flag = True ca_len = len(report['reporting_period']['names']) real_timestamps_len = timestamps_data_not_equal_0( report['parameters']['timestamps']) table_row = (current_row_number + 1) + ca_len * 6 + real_timestamps_len * 7 + 1 if "timestamps" not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0: has_detail_data_flag = False if has_detail_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + 'Detailed Data' ws.row_dimensions[table_row].height = 60 ws['B' + str(table_row)].fill = table_fill ws['B' + str(table_row)].font = title_font ws['B' + str(table_row)].border = f_border ws['B' + str(table_row)].alignment = c_c_alignment ws['B' + str(table_row)] = 'Datetime' time = times[0] has_data = False max_row = 0 if len(time) > 0: has_data = True max_row = table_row + len(time) if has_data: for i in range(0, len(time)): col = 'B' row = str(table_row + 1 + i) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = time[i] ws[col + row].border = f_border for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(table_row)].fill = table_fill ws[col + str(table_row)].font = title_font ws[col + str(table_row)].alignment = c_c_alignment ws[col + str(table_row)] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + str(table_row)].border = f_border # 39 data time = times[i] time_len = len(time) for j in range(0, time_len): row = str(table_row + 1 + j) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round( reporting_period_data['values'][i][j], 2) ws[col + row].border = f_border line = LineChart() line.title = 'Reporting Period Income - ' + reporting_period_data['names'][i] + \ " (" + reporting_period_data['units'][i] + ")" labels = Reference(ws, min_col=2, min_row=table_row + 1, max_row=max_row) line_data = Reference(ws, min_col=3 + i, min_row=table_row, max_row=max_row) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = True line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(current_row_number + 1 + 6 * i) chart_start_row_number = current_row_number ws.add_chart(line, chart_cell) row = str(max_row + 1) ws['B' + row].font = title_font ws['B' + row].alignment = c_c_alignment ws['B' + row] = 'Subtotal' ws['B' + row].border = f_border col = '' for i in range(0, ca_len): col = chr(ord('C') + i) row = str(max_row + 1) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(reporting_period_data['subtotals'][i], 2) ws[col + row].border = f_border col = chr(ord(col) + 1) ws[col + str(table_row)].fill = table_fill ws[col + str(table_row)].font = title_font ws[col + str(table_row)].alignment = c_c_alignment ws[col + str(table_row)] = 'Total (' + report['reporting_period'][ 'total_unit'] + ')' ws[col + str(table_row)].border = f_border total_sum = 0 for j in range(0, len(time)): row = str(table_row + 1 + j) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment periodic_sum = reporting_period_values_periodic_sum( reporting_period_data, j, ca_len) total_sum += periodic_sum ws[col + row] = round(periodic_sum, 2) ws[col + row].border = f_border row = str(table_row + 1 + len(time)) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(total_sum, 2) ws[col + row].border = f_border else: for i in range(37, 69 + 1): ws.row_dimensions[i].height = 0.1 #################################################################################################################### has_associated_equipment_flag = True time_len = len(times[0]) current_row_number = time_len + table_row + 3 if "associated_equipment" not in report.keys() or \ "energy_category_names" not in report['associated_equipment'].keys() or \ len(report['associated_equipment']["energy_category_names"]) == 0 \ or 'associated_equipment_names_array' not in report['associated_equipment'].keys() \ or report['associated_equipment']['associated_equipment_names_array'] is None \ or len(report['associated_equipment']['associated_equipment_names_array']) == 0 \ or len(report['associated_equipment']['associated_equipment_names_array'][0]) == 0: has_associated_equipment_flag = False if has_associated_equipment_flag: associated_equipment = report['associated_equipment'] ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + 'Associated Equipment Data' current_row_number += 1 ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = name_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = 'Associated Equipment' ca_len = len(associated_equipment['energy_category_names']) for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" col_subtotal = chr(ord('C') + ca_len) ws[col_subtotal + str(current_row_number)].fill = table_fill ws[col_subtotal + str(current_row_number)].font = name_font ws[col_subtotal + str(current_row_number)].alignment = c_c_alignment ws[col_subtotal + str(current_row_number)].border = f_border ws[col_subtotal + str(current_row_number )] = 'Total (' + report['reporting_period']['total_unit'] + ')' associated_equipment_len = len( associated_equipment['associated_equipment_names_array'][0]) for i in range(0, associated_equipment_len): current_row_number += 1 row = str(current_row_number) ws['B' + row].font = title_font ws['B' + row].alignment = c_c_alignment ws['B' + row] = associated_equipment[ 'associated_equipment_names_array'][0][i] ws['B' + row].border = f_border subtotal = Decimal(0.0) for j in range(0, ca_len): col = chr(ord('C') + j) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round( associated_equipment['subtotals_array'][j][i], 2) ws[col + row].border = f_border subtotal += associated_equipment['subtotals_array'][j][i] ws[col_subtotal + row].font = title_font ws[col_subtotal + row].alignment = c_c_alignment ws[col_subtotal + row] = round(subtotal, 2) ws[col_subtotal + row].border = f_border print(subtotal) #################################################################################################################### current_sheet_parameters_row_number = chart_start_row_number + ca_len * 6 + 1 has_parameters_names_and_timestamps_and_values_data = True if 'parameters' not in report.keys() or \ report['parameters'] is None or \ 'names' not in report['parameters'].keys() or \ report['parameters']['names'] is None or \ len(report['parameters']['names']) == 0 or \ 'timestamps' not in report['parameters'].keys() or \ report['parameters']['timestamps'] is None or \ len(report['parameters']['timestamps']) == 0 or \ 'values' not in report['parameters'].keys() or \ report['parameters']['values'] is None or \ len(report['parameters']['values']) == 0 or \ timestamps_data_all_equal_0(report['parameters']['timestamps']): has_parameters_names_and_timestamps_and_values_data = False if has_parameters_names_and_timestamps_and_values_data: ################################################################################################################ # new worksheet ################################################################################################################ parameters_data = report['parameters'] parameters_names_len = len(parameters_data['names']) file_name = (re.sub(r'[^A-Z]', '', ws.title)) + '_' parameters_ws = wb.create_sheet(file_name + 'Parameters') parameters_timestamps_data_max_len = \ get_parameters_timestamps_lists_max_len(list(parameters_data['timestamps'])) # Row height parameters_ws.row_dimensions[1].height = 102 for i in range(2, 7 + 1): parameters_ws.row_dimensions[i].height = 42 for i in range(8, parameters_timestamps_data_max_len + 10): parameters_ws.row_dimensions[i].height = 60 # Col width parameters_ws.column_dimensions['A'].width = 1.5 parameters_ws.column_dimensions['B'].width = 25.0 for i in range(3, 12 + parameters_names_len * 3): parameters_ws.column_dimensions[format_cell.get_column_letter( i)].width = 15.0 # Img img = Image("excelexporters/myems.png") parameters_ws.add_image(img, 'A1') # Title parameters_ws['B3'].alignment = b_r_alignment parameters_ws['B3'] = 'Name:' parameters_ws['C3'].border = b_border parameters_ws['C3'].alignment = b_c_alignment parameters_ws['C3'] = name parameters_ws['D3'].alignment = b_r_alignment parameters_ws['D3'] = 'Period:' parameters_ws['E3'].border = b_border parameters_ws['E3'].alignment = b_c_alignment parameters_ws['E3'] = period_type parameters_ws['B4'].alignment = b_r_alignment parameters_ws['B4'] = 'Reporting Start Datetime:' parameters_ws['C4'].border = b_border parameters_ws['C4'].alignment = b_c_alignment parameters_ws['C4'] = reporting_start_datetime_local parameters_ws['D4'].alignment = b_r_alignment parameters_ws['D4'] = 'Reporting End Datetime:' parameters_ws['E4'].border = b_border parameters_ws['E4'].alignment = b_c_alignment parameters_ws['E4'] = reporting_end_datetime_local parameters_ws_current_row_number = 6 parameters_ws['B' + str(parameters_ws_current_row_number)].font = title_font parameters_ws[ 'B' + str(parameters_ws_current_row_number)] = name + ' ' + 'Parameters' parameters_ws_current_row_number += 1 parameters_table_start_row_number = parameters_ws_current_row_number parameters_ws.row_dimensions[ parameters_ws_current_row_number].height = 80 parameters_ws_current_row_number += 1 table_current_col_number = 2 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border parameters_ws[col + str(parameters_ws_current_row_number - 1)].font = name_font parameters_ws[col + str(parameters_ws_current_row_number - 1)].alignment = c_c_alignment parameters_ws[col + str(parameters_ws_current_row_number - 1)] = parameters_data['names'][i] table_current_row_number = parameters_ws_current_row_number for j, value in enumerate(list(parameters_data['timestamps'][i])): col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = value col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = round( parameters_data['values'][i][j], 2) table_current_row_number += 1 table_current_col_number = table_current_col_number + 3 ################################################################################################################ # parameters chart and parameters table ################################################################################################################ ws['B' + str(current_sheet_parameters_row_number)].font = title_font ws['B' + str( current_sheet_parameters_row_number)] = name + ' ' + 'Parameters' current_sheet_parameters_row_number += 1 chart_start_row_number = current_sheet_parameters_row_number col_index = 0 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue line = LineChart() data_col = 3 + col_index * 3 labels_col = 2 + col_index * 3 col_index += 1 line.title = 'Parameters - ' + \ parameters_ws.cell(row=parameters_table_start_row_number, column=data_col).value labels = Reference(parameters_ws, min_col=labels_col, min_row=parameters_table_start_row_number + 1, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line_data = Reference( parameters_ws, min_col=data_col, min_row=parameters_table_start_row_number, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = False line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number) chart_start_row_number += 6 ws.add_chart(line, chart_cell) current_sheet_parameters_row_number = chart_start_row_number current_sheet_parameters_row_number += 1 #################################################################################################################### filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active ws.title = "StoreEnergyItem" # Row height ws.row_dimensions[1].height = 102 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 42 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('L')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Arial', size=15, bold=True) title_font = Font(name='Arial', size=15, bold=True) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000')) b_border = Border(bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") ws.add_image(img, 'A1') # Title ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'] = name ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'] = period_type ws['B4'].alignment = b_r_alignment ws['B4'] = 'Reporting Start Datetime:' ws['C4'].border = b_border ws['C4'].alignment = b_c_alignment ws['C4'] = reporting_start_datetime_local ws['D4'].alignment = b_r_alignment ws['D4'] = 'Reporting End Datetime:' ws['E4'].border = b_border ws['E4'].alignment = b_c_alignment ws['E4'] = reporting_end_datetime_local if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename #################################################################################################################### current_row_number = 6 reporting_period_data = report['reporting_period'] has_names_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_names_data_flag = False if has_names_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str( current_row_number)] = name + ' ' + 'Reporting Period Consumption' current_row_number += 1 category = reporting_period_data['names'] ca_len = len(category) ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].border = f_border col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = \ reporting_period_data['names'][i] + " " + reporting_period_data['energy_category_names'][i] + \ " (" + reporting_period_data['units'][i] + ")" col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '消耗' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = 'Per Unit Area' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round( reporting_period_data['subtotals_per_unit_area'][i], 2) col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = 'Increment Rate' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = str( round(reporting_period_data['increment_rates'][i] * 100, 2)) + '%' \ if reporting_period_data['increment_rates'][i] is not None else '-' col = chr(ord(col) + 1) current_row_number += 2 category_dict = group_by_category( reporting_period_data['energy_category_names']) for category_dict_name, category_dict_values in category_dict.items(): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + category_dict_name + ' ' + \ '(' + reporting_period_data['units'][category_dict_values[0]] + ') by Energy Item' current_row_number += 1 table_start_row_number = current_row_number ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = '消耗' current_row_number += 1 for i in category_dict_values: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 3) current_row_number += 1 table_end_row_number = current_row_number - 1 pie = PieChart() pie.title = name + ' ' + category_dict_name + ' ' + \ '(' + reporting_period_data['units'][category_dict_values[0]] + ') by Energy Item' labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 6.6 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True ws.add_chart(pie, 'D' + str(table_start_row_number)) if len(category_dict_values) < 4: current_row_number = current_row_number - len( category_dict_values) + 4 current_row_number += 1 #################################################################################################################### has_values_data = True has_timestamps_data = True if 'values' not in reporting_period_data.keys() or \ reporting_period_data['values'] is None or \ len(reporting_period_data['values']) == 0: has_values_data = False if 'timestamps' not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0 or \ len(reporting_period_data['timestamps'][0]) == 0: has_timestamps_data = False current_row_number += 1 chart_start_row_number = current_row_number if has_values_data and has_timestamps_data: ca_len = len(reporting_period_data['names']) time = reporting_period_data['timestamps'][0] parameters_names_len = len(report['parameters']['names']) parameters_parameters_datas_len = 0 ws['B' + str(current_row_number - 1)].font = title_font ws['B' + str(current_row_number - 1)] = name + ' ' + 'Detailed Data' for i in range(0, parameters_names_len): if len(report['parameters']['timestamps'][i]) == 0: continue parameters_parameters_datas_len += 1 current_row_number = current_row_number + ( ca_len + parameters_parameters_datas_len) * 6 + 2 detail_data_table_start_row_number = current_row_number ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = 'Datetime' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" col = chr(ord(col) + 1) current_row_number += 1 for i in range(0, len(time)): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = time[i] col = 'C' for j in range(0, ca_len): ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['values'][j][i], 2) \ if reporting_period_data['values'][j][i] is not None else 0.00 col = chr(ord(col) + 1) current_row_number += 1 table_end_row_number = current_row_number - 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = 'Subtotal' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) col = chr(ord(col) + 1) current_row_number += 2 format_time_width_number = 1.0 min_len_number = 1.0 min_width_number = 11.0 if period_type == 'hourly': format_time_width_number = 4.0 min_len_number = 2 min_width_number = 12.0 elif period_type == 'daily': format_time_width_number = 2.5 min_len_number = 4 min_width_number = 14.0 elif period_type == 'monthly': format_time_width_number = 2.1 min_len_number = 4 min_width_number = 12.4 elif period_type == 'yearly': format_time_width_number = 1.5 min_len_number = 5 min_width_number = 11.5 for i in range(0, ca_len): line = LineChart() line.title = 'Reporting Period Consumption - ' + \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" labels = Reference(ws, min_col=2, min_row=detail_data_table_start_row_number + 1, max_row=table_end_row_number) line_data = Reference(ws, min_col=3 + i, min_row=detail_data_table_start_row_number, max_row=table_end_row_number) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = format_time_width_number * len(time) if len( time) > min_len_number else min_width_number if line.width > 24: line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = True line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number + 6 * i) ws.add_chart(line, chart_cell) #################################################################################################################### has_parameters_names_and_timestamps_and_values_data = True ca_len = len(report['reporting_period']['names']) current_sheet_parameters_row_number = chart_start_row_number + ca_len * 6 if 'parameters' not in report.keys() or \ report['parameters'] is None or \ 'names' not in report['parameters'].keys() or \ report['parameters']['names'] is None or \ len(report['parameters']['names']) == 0 or \ 'timestamps' not in report['parameters'].keys() or \ report['parameters']['timestamps'] is None or \ len(report['parameters']['timestamps']) == 0 or \ 'values' not in report['parameters'].keys() or \ report['parameters']['values'] is None or \ len(report['parameters']['values']) == 0 or \ timestamps_data_all_equal_0(report['parameters']['timestamps']): has_parameters_names_and_timestamps_and_values_data = False if has_parameters_names_and_timestamps_and_values_data: ################################################################################################################ # new worksheet ################################################################################################################ parameters_data = report['parameters'] parameters_names_len = len(parameters_data['names']) file_name = "Store" + re.sub(r'[^A-Z]', '', ws.title.strip('S')) + "_" parameters_ws = wb.create_sheet(file_name + 'Parameters') parameters_timestamps_data_max_len = \ get_parameters_timestamps_lists_max_len(list(parameters_data['timestamps'])) # Row height parameters_ws.row_dimensions[1].height = 102 for i in range(2, 7 + 1): parameters_ws.row_dimensions[i].height = 42 for i in range(8, parameters_timestamps_data_max_len + 10): parameters_ws.row_dimensions[i].height = 60 # Col width parameters_ws.column_dimensions['A'].width = 1.5 parameters_ws.column_dimensions['B'].width = 25.0 for i in range(3, 12 + parameters_names_len * 3): parameters_ws.column_dimensions[format_cell.get_column_letter( i)].width = 15.0 # Img img = Image("excelexporters/myems.png") parameters_ws.add_image(img, 'A1') # Title parameters_ws['B3'].alignment = b_r_alignment parameters_ws['B3'] = 'Name:' parameters_ws['C3'].border = b_border parameters_ws['C3'].alignment = b_c_alignment parameters_ws['C3'] = name parameters_ws['D3'].alignment = b_r_alignment parameters_ws['D3'] = 'Period:' parameters_ws['E3'].border = b_border parameters_ws['E3'].alignment = b_c_alignment parameters_ws['E3'] = period_type parameters_ws['B4'].alignment = b_r_alignment parameters_ws['B4'] = 'Reporting Start Datetime:' parameters_ws['C4'].border = b_border parameters_ws['C4'].alignment = b_c_alignment parameters_ws['C4'] = reporting_start_datetime_local parameters_ws['D4'].alignment = b_r_alignment parameters_ws['D4'] = 'Reporting End Datetime:' parameters_ws['E4'].border = b_border parameters_ws['E4'].alignment = b_c_alignment parameters_ws['E4'] = reporting_end_datetime_local parameters_ws_current_row_number = 6 parameters_ws['B' + str(parameters_ws_current_row_number)].font = title_font parameters_ws[ 'B' + str(parameters_ws_current_row_number)] = name + ' ' + 'Parameters' parameters_ws_current_row_number += 1 parameters_table_start_row_number = parameters_ws_current_row_number parameters_ws.row_dimensions[ parameters_ws_current_row_number].height = 80 parameters_ws_current_row_number += 1 table_current_col_number = 2 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border parameters_ws[col + str(parameters_ws_current_row_number - 1)].font = name_font parameters_ws[col + str(parameters_ws_current_row_number - 1)].alignment = c_c_alignment parameters_ws[col + str(parameters_ws_current_row_number - 1)] = parameters_data['names'][i] table_current_row_number = parameters_ws_current_row_number for j, value in enumerate(list(parameters_data['timestamps'][i])): col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = value col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = round( parameters_data['values'][i][j], 2) table_current_row_number += 1 table_current_col_number = table_current_col_number + 3 ################################################################################################################ # parameters chart and parameters table ################################################################################################################ ws['B' + str(current_sheet_parameters_row_number)].font = title_font ws['B' + str( current_sheet_parameters_row_number)] = name + ' ' + 'Parameters' current_sheet_parameters_row_number += 1 chart_start_row_number = current_sheet_parameters_row_number col_index = 0 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue line = LineChart() data_col = 3 + col_index * 3 labels_col = 2 + col_index * 3 col_index += 1 line.title = 'Parameters - ' + \ parameters_ws.cell(row=parameters_table_start_row_number, column=data_col).value labels = Reference(parameters_ws, min_col=labels_col, min_row=parameters_table_start_row_number + 1, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line_data = Reference( parameters_ws, min_col=data_col, min_row=parameters_table_start_row_number, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = False line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number) chart_start_row_number += 6 ws.add_chart(line, chart_cell) current_sheet_parameters_row_number = chart_start_row_number current_sheet_parameters_row_number += 1 filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active # Row height ws.row_dimensions[1].height = 102 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 42 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('L')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Constantia', size=15, bold=True) title_font = Font(name='宋体', size=15, bold=True) data_font = Font(name='Franklin Gothic Book', size=11) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000') ) b_border = Border( bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_r_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") img.width = img.width * 0.85 img.height = img.height * 0.85 # img = Image("myems.png") ws.add_image(img, 'B1') # Title ws.row_dimensions[3].height = 60 ws['B3'].font = name_font ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'].font = name_font ws['C3'] = name ws['D3'].font = name_font ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'].font = name_font ws['E3'] = period_type ws['F3'].font = name_font ws['F3'].alignment = b_r_alignment ws['F3'] = 'Date:' ws['G3'].border = b_border ws['G3'].alignment = b_c_alignment ws['G3'].font = name_font ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local ws.merge_cells("G3:H3") if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename ################################## reporting_period_data = report['reporting_period'] has_cost_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_cost_data_flag = False if has_cost_data_flag: ws['B5'].font = title_font ws['B5'] = name + ' 报告期收入' category = reporting_period_data['names'] ca_len = len(category) ws.row_dimensions[7].height = 60 ws['B6'].fill = table_fill ws['B6'].border = f_border ws['B7'].font = title_font ws['B7'].alignment = c_c_alignment ws['B7'] = '报告期收入' ws['B7'].border = f_border ws['B8'].font = title_font ws['B8'].alignment = c_c_alignment ws['B8'] = '环比' ws['B8'].border = f_border col = '' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + '6'].fill = table_fill ws[col + '6'].font = name_font ws[col + '6'].alignment = c_c_alignment ws[col + '6'] = reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" ws[col + '6'].border = f_border ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = round(reporting_period_data['subtotals'][i], 2) ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \ if reporting_period_data['increment_rates'][i] is not None else "-" ws[col + '8'].border = f_border col = chr(ord(col) + 1) ws[col + '6'].fill = table_fill ws[col + '6'].font = name_font ws[col + '6'].alignment = c_c_alignment ws[col + '6'] = "总计 (" + reporting_period_data['total_unit'] + ")" ws[col + '6'].border = f_border ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = round(reporting_period_data['total'], 2) ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = str(round(reporting_period_data['total_increment_rate'] * 100, 2)) + "%" \ if reporting_period_data['total_increment_rate'] is not None else "-" ws[col + '8'].border = f_border else: for i in range(6, 8 + 1): ws.row_dimensions[i].height = 0.1 ################################## current_row_number = 10 has_subtotals_data_flag = True if "subtotals" not in reporting_period_data.keys() or \ reporting_period_data['subtotals'] is None or \ len(reporting_period_data['subtotals']) == 0: has_subtotals_data_flag = False if has_subtotals_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 收入占比' current_row_number += 1 table_start_row_number = current_row_number ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = name_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = '收入' ws['D' + str(current_row_number)].fill = table_fill ws['D' + str(current_row_number)].font = name_font ws['D' + str(current_row_number)].alignment = c_c_alignment ws['D' + str(current_row_number)].border = f_border ws['D' + str(current_row_number)] = '收入占比' current_row_number += 1 ca_len = len(reporting_period_data['names']) wssum = Decimal(0.0) for i in range(0, ca_len): wssum = round(reporting_period_data['subtotals'][i], 2) + wssum for i in range(0, ca_len): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = reporting_period_data['names'][i] ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].font = title_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 2) ws['D' + str(current_row_number)].font = title_font ws['D' + str(current_row_number)].alignment = c_c_alignment ws['D' + str(current_row_number)].border = f_border ws['D' + str(current_row_number)] = '{:.2%}'.format(round( reporting_period_data['subtotals'][i], 2) / wssum) if wssum is not None and wssum != Decimal(0.0) \ else " " current_row_number += 1 table_end_row_number = current_row_number - 1 pie = PieChart() pie.title = name + ' 收入占比' labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 6.6 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True table_cell = 'F' + str(table_start_row_number - 1) ws.add_chart(pie, table_cell) if ca_len < 4: current_row_number = current_row_number - ca_len + 4 else: for i in range(13, 22 + 1): ws.row_dimensions[i].height = 0.1 ############################################# current_row_number = 14 reporting_period_data = report['reporting_period'] times = reporting_period_data['timestamps'] has_detail_data_flag = True ca_len = len(report['reporting_period']['names']) table_row = (current_row_number + 1) + ca_len * 6 if "timestamps" not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0: has_detail_data_flag = False if has_detail_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 详细数据' ws.row_dimensions[table_row].height = 60 ws['B' + str(table_row)].fill = table_fill ws['B' + str(table_row)].font = title_font ws['B' + str(table_row)].border = f_border ws['B' + str(table_row)].alignment = c_c_alignment ws['B' + str(table_row)] = '日期时间' time = times[0] has_data = False max_row = 0 if len(time) > 0: has_data = True max_row = table_row + len(time) if has_data: for i in range(0, len(time)): col = 'B' row = str(table_row + 1 + i) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = time[i] ws[col + row].border = f_border for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(table_row)].fill = table_fill ws[col + str(table_row)].font = title_font ws[col + str(table_row)].alignment = c_c_alignment ws[col + str(table_row)] = reporting_period_data['names'][i] + " (" + reporting_period_data['units'][ i] + ")" ws[col + str(table_row)].border = f_border # 39 data time = times[i] time_len = len(time) for j in range(0, time_len): row = str(table_row + 1 + j) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(reporting_period_data['values'][i][j], 2) ws[col + row].border = f_border line = LineChart() line.title = \ '报告期收入 - ' + reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" labels = Reference(ws, min_col=2, min_row=table_row + 1, max_row=max_row) line_data = Reference(ws, min_col=3 + i, min_row=table_row, max_row=max_row) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = True line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(current_row_number + 1 + 6 * i) ws.add_chart(line, chart_cell) row = str(max_row + 1) ws['B' + row].font = title_font ws['B' + row].alignment = c_c_alignment ws['B' + row] = '小计' ws['B' + row].border = f_border col = '' for i in range(0, ca_len): col = chr(ord('C') + i) row = str(max_row + 1) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(reporting_period_data['subtotals'][i], 2) ws[col + row].border = f_border col = chr(ord(col) + 1) ws[col + str(table_row)].fill = table_fill ws[col + str(table_row)].font = title_font ws[col + str(table_row)].alignment = c_c_alignment ws[col + str(table_row)] = '总计 (' + report['reporting_period']['total_unit'] + ')' ws[col + str(table_row)].border = f_border total_sum = 0 for j in range(0, len(time)): row = str(table_row + 1 + j) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment every_day_sum = reporting_period_values_every_day_sum(reporting_period_data, j, ca_len) total_sum += every_day_sum ws[col + row] = round(every_day_sum, 2) ws[col + row].border = f_border row = str(table_row + 1 + len(time)) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(total_sum, 2) ws[col + row].border = f_border else: for i in range(37, 69 + 1): ws.row_dimensions[i].height = 0.1 ##################################### has_associated_equipment_flag = True time_len = len(times[0]) current_row_number = time_len + table_row + 3 if "associated_equipment" not in report.keys() or \ "energy_category_names" not in report['associated_equipment'].keys() or \ len(report['associated_equipment']["energy_category_names"]) == 0 \ or 'associated_equipment_names_array' not in report['associated_equipment'].keys() \ or report['associated_equipment']['associated_equipment_names_array'] is None \ or len(report['associated_equipment']['associated_equipment_names_array']) == 0 \ or len(report['associated_equipment']['associated_equipment_names_array'][0]) == 0: has_associated_equipment_flag = False if has_associated_equipment_flag: associated_equipment = report['associated_equipment'] ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 相关设备数据' current_row_number += 1 ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = name_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '相关设备' ca_len = len(associated_equipment['energy_category_names']) for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" col_subtotal = chr(ord('C') + ca_len) ws[col_subtotal + str(current_row_number)].fill = table_fill ws[col_subtotal + str(current_row_number)].font = name_font ws[col_subtotal + str(current_row_number)].alignment = c_c_alignment ws[col_subtotal + str(current_row_number)].border = f_border ws[col_subtotal + str(current_row_number)] = '总计 (' + report['reporting_period']['total_unit'] + ')' associated_equipment_len = len(associated_equipment['associated_equipment_names_array'][0]) for i in range(0, associated_equipment_len): current_row_number += 1 row = str(current_row_number) ws['B' + row].font = title_font ws['B' + row].alignment = c_c_alignment ws['B' + row] = associated_equipment['associated_equipment_names_array'][0][i] ws['B' + row].border = f_border subtotal = Decimal(0.0) for j in range(0, ca_len): col = chr(ord('C') + j) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(associated_equipment['subtotals_array'][j][i], 2) ws[col + row].border = f_border subtotal += associated_equipment['subtotals_array'][j][i] ws[col_subtotal + row].font = title_font ws[col_subtotal + row].alignment = c_c_alignment ws[col_subtotal + row] = round(subtotal, 2) ws[col_subtotal + row].border = f_border print(subtotal) filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active # Row height ws.row_dimensions[1].height = 102 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 42 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('L')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Constantia', size=15, bold=True) title_font = Font(name='宋体', size=15, bold=True) data_font = Font(name='Franklin Gothic Book', size=11) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000')) b_border = Border(bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_r_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") # img = Image("myems.png") img.width = img.width * 1.06 img.height = img.height * 1.06 ws.add_image(img, 'B1') # Title ws.row_dimensions[3].height = 60 ws['B3'].font = name_font ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'].font = name_font ws['C3'] = name ws['D3'].font = name_font ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'].font = name_font ws['E3'] = period_type ws['F3'].font = name_font ws['F3'].alignment = b_r_alignment ws['F3'] = 'Date:' ws['G3'].border = b_border ws['G3'].alignment = b_c_alignment ws['G3'].font = name_font ws['G3'] = reporting_start_datetime_local[: 10] + "__" + reporting_end_datetime_local[: 10] ws.merge_cells("G3:H3") if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename ################################################# # First: 能耗分析 # 6: title # 7: table title # 8~10 table_data # Total: 5 rows # if has not energy data: set low height for rows ################################################# reporting_period_data = report['reporting_period'] has_energy_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_energy_data_flag = False if has_energy_data_flag: ws['B6'].font = title_font ws['B6'] = name + ' 能耗分析' category = reporting_period_data['names'] ca_len = len(category) ws.row_dimensions[7].height = 60 ws['B7'].fill = table_fill ws['B7'].border = f_border ws['B8'].font = title_font ws['B8'].alignment = c_c_alignment ws['B8'] = '能耗' ws['B8'].border = f_border ws['B9'].font = title_font ws['B9'].alignment = c_c_alignment ws['B9'] = '环比' ws['B9'].border = f_border col = '' for i in range(0, ca_len): col = chr(ord('C') + i) row = '7' cell = col + row ws[col + '7'].fill = table_fill ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = round(reporting_period_data['subtotals'][i], 2) ws[col + '8'].border = f_border ws[col + '9'].font = name_font ws[col + '9'].alignment = c_c_alignment ws[col + '9'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \ if reporting_period_data['increment_rates'][i] is not None else "-" ws[col + '9'].border = f_border # TCE TCO2E end_col = col # TCE tce_col = chr(ord(end_col) + 1) ws[tce_col + '7'].fill = table_fill ws[tce_col + '7'].font = name_font ws[tce_col + '7'].alignment = c_c_alignment ws[tce_col + '7'] = "吨标准煤 (TCE)" ws[tce_col + '7'].border = f_border ws[tce_col + '8'].font = name_font ws[tce_col + '8'].alignment = c_c_alignment ws[tce_col + '8'] = round( reporting_period_data['total_in_kgce'] / 1000, 2) ws[tce_col + '8'].border = f_border ws[tce_col + '9'].font = name_font ws[tce_col + '9'].alignment = c_c_alignment ws[tce_col + '9'] = str(round(reporting_period_data['increment_rate_in_kgce'] * 100, 2)) + "%" \ if reporting_period_data['increment_rate_in_kgce'] is not None else "-" ws[tce_col + '9'].border = f_border # TCO2E tco2e_col = chr(ord(end_col) + 2) ws[tco2e_col + '7'].fill = table_fill ws[tco2e_col + '7'].font = name_font ws[tco2e_col + '7'].alignment = c_c_alignment ws[tco2e_col + '7'] = "吨二氧化碳排放 (TCO2E)" ws[tco2e_col + '7'].border = f_border ws[tco2e_col + '8'].font = name_font ws[tco2e_col + '8'].alignment = c_c_alignment ws[tco2e_col + '8'] = round( reporting_period_data['total_in_kgco2e'] / 1000, 2) ws[tco2e_col + '8'].border = f_border ws[tco2e_col + '9'].font = name_font ws[tco2e_col + '9'].alignment = c_c_alignment ws[tco2e_col + '9'] = str(round(reporting_period_data['increment_rate_in_kgco2e'] * 100, 2)) + "%" \ if reporting_period_data['increment_rate_in_kgco2e'] is not None else "-" ws[tco2e_col + '9'].border = f_border else: for i in range(6, 9 + 1): ws.row_dimensions[i].height = 0.1 ################################################# # Second: 分时电耗 # 12: title # 13: table title # 14~17 table_data # Total: 6 rows ################################################ has_ele_peak_flag = True if "toppeaks" not in reporting_period_data.keys() or \ reporting_period_data['toppeaks'] is None or \ len(reporting_period_data['toppeaks']) == 0: has_ele_peak_flag = False if has_ele_peak_flag: ws['B12'].font = title_font ws['B12'] = name + ' 分时电耗' ws.row_dimensions[13].height = 60 ws['B13'].fill = table_fill ws['B13'].font = name_font ws['B13'].alignment = c_c_alignment ws['B13'].border = f_border ws['C13'].fill = table_fill ws['C13'].font = name_font ws['C13'].alignment = c_c_alignment ws['C13'].border = f_border ws['C13'] = '分时电耗' ws['B14'].font = title_font ws['B14'].alignment = c_c_alignment ws['B14'] = '尖' ws['B14'].border = f_border ws['C14'].font = title_font ws['C14'].alignment = c_c_alignment ws['C14'].border = f_border ws['C14'] = round(reporting_period_data['toppeaks'][0], 2) ws['B15'].font = title_font ws['B15'].alignment = c_c_alignment ws['B15'] = '峰' ws['B15'].border = f_border ws['C15'].font = title_font ws['C15'].alignment = c_c_alignment ws['C15'].border = f_border ws['C15'] = round(reporting_period_data['onpeaks'][0], 2) ws['B16'].font = title_font ws['B16'].alignment = c_c_alignment ws['B16'] = '平' ws['B16'].border = f_border ws['C16'].font = title_font ws['C16'].alignment = c_c_alignment ws['C16'].border = f_border ws['C16'] = round(reporting_period_data['midpeaks'][0], 2) ws['B17'].font = title_font ws['B17'].alignment = c_c_alignment ws['B17'] = '谷' ws['B17'].border = f_border ws['C17'].font = title_font ws['C17'].alignment = c_c_alignment ws['C17'].border = f_border ws['C17'] = round(reporting_period_data['offpeaks'][0], 2) pie = PieChart() pie.title = name + ' 分时电耗' labels = Reference(ws, min_col=2, min_row=14, max_row=17) pie_data = Reference(ws, min_col=3, min_row=13, max_row=17) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 7.25 # cm 1.05*5 1.05cm = 30 pt pie.width = 9 # pie.title = "Pies sold by category" s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False # 标签显示 s1.dLbls.showVal = True # 数量显示 s1.dLbls.showPercent = True # 百分比显示 # s1 = CharacterProperties(sz=1800) # 图表中字体大小 *100 ws.add_chart(pie, "D13") else: for i in range(12, 18 + 1): ws.row_dimensions[i].height = 0.1 # end_row 10 # start_row 12 ################################################ # Third: 子空间能耗 # 19: title # 20: table title # 21~24 table_data # Total: 6 rows ################################################ has_child_flag = True # Judge if the space has child space, if not, delete it. if "child_space" not in report.keys() or "energy_category_names" not in report['child_space'].keys() or \ len(report['child_space']["energy_category_names"]) == 0 \ or 'child_space_names_array' not in report['child_space'].keys() \ or report['child_space']['energy_category_names'] is None \ or len(report['child_space']['child_space_names_array']) == 0 \ or len(report['child_space']['child_space_nchild_space_names_arrayames_array'][0]) == 0: has_child_flag = False current_row_number = 19 if has_child_flag: child = report['child_space'] child_spaces = child['child_space_names_array'][0] child_subtotals = child['subtotals_array'][0] ws['B19'].font = title_font ws['B19'] = name + ' 子空间能耗' ws.row_dimensions[20].height = 60 ws['B20'].fill = table_fill ws['B20'].border = f_border ca_len = len(child['energy_category_names']) table_start_row_number = 20 for i in range(0, ca_len): row = chr(ord('C') + i) ws[row + '20'].fill = table_fill ws[row + '20'].font = title_font ws[row + '20'].alignment = c_c_alignment ws[row + '20'].border = f_border ws[row + '20'] = child['energy_category_names'][i] + ' (' + child[ 'units'][i] + ')' space_len = len(child['child_space_names_array'][0]) for i in range(0, space_len): row = str(i + 21) ws['B' + row].font = name_font ws['B' + row].alignment = c_c_alignment ws['B' + row] = child['child_space_names_array'][0][i] ws['B' + row].border = f_border for j in range(0, ca_len): col = chr(ord('C') + j) ws[col + row].font = name_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(child['subtotals_array'][j][i], 2) ws[col + row].border = f_border table_end_row_number = 20 + space_len chart_start_row_number = 20 + space_len + 1 for i in range(0, ca_len): # pie # 25~30: pie pie = PieChart() pie.title = ws.cell(column=3 + i, row=table_start_row_number).value labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 6.6 # cm 1.05*5 1.05cm = 30 pt pie.width = 8 # pie.title = "Pies sold by category" s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False # 标签显示 s1.dLbls.showVal = True # 数量显示 s1.dLbls.showPercent = True # 百分比显示 # s1 = CharacterProperties(sz=1800) # 图表中字体大小 *100 chart_cell = '' if i % 2 == 0: chart_cell = 'B' + str(chart_start_row_number) else: chart_cell = 'E' + str(chart_start_row_number) chart_start_row_number += 5 # ws.add_chart(pie, chart_cell) # chart_col = chr(ord('B') + 2 * j) # chart_cell = chart_col + '25' ws.add_chart(pie, chart_cell) current_row_number = chart_start_row_number if ca_len % 2 == 1: current_row_number += 5 current_row_number += 1 ################################################ # Fourth: 能耗详情 # current_row_number: title # current_row_number+1 ~ current_row_number+1+ca_len*6-1: line # current_row_number+1+ca_len*6: table title # current_row_number+1+ca_len*6~: table_data ################################################ reporting_period_data = report['reporting_period'] times = reporting_period_data['timestamps'] has_detail_data_flag = True ca_len = len(report['reporting_period']['names']) table_row = current_row_number + 1 + ca_len * 6 chart_start_row_number = current_row_number + 1 if "timestamps" not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0: has_detail_data_flag = False if has_detail_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 详细数据' ws.row_dimensions[table_row].height = 60 ws['B' + str(table_row)].fill = table_fill ws['B' + str(table_row)].font = title_font ws['B' + str(table_row)].border = f_border ws['B' + str(table_row)].alignment = c_c_alignment ws['B' + str(table_row)] = '日期时间' time = times[0] has_data = False max_row = 0 if len(time) > 0: has_data = True max_row = table_row + len(time) print("max_row", max_row) if has_data: for i in range(0, len(time)): col = 'B' row = str(table_row + 1 + i) # col = chr(ord('B') + i) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = time[i] ws[col + row].border = f_border for i in range(0, ca_len): # 38 title col = chr(ord('C') + i) ws[col + str(table_row)].fill = table_fill ws[col + str(table_row)].font = title_font ws[col + str(table_row)].alignment = c_c_alignment ws[col + str(table_row)] = reporting_period_data['names'][i] + \ " (" + reporting_period_data['units'][i] + ")" ws[col + str(table_row)].border = f_border # 39 data time = times[i] time_len = len(time) for j in range(0, time_len): row = str(table_row + 1 + j) # col = chr(ord('B') + i) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round( reporting_period_data['values'][i][j], 2) ws[col + row].border = f_border current_row_number = table_row + 1 + len(times[0]) ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '小计' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) # line # 39~: line line = LineChart() line.title = '报告期消耗 - ' + ws.cell(column=3 + i, row=table_row).value labels = Reference(ws, min_col=2, min_row=table_row + 1, max_row=max_row) line_data = Reference(ws, min_col=3 + i, min_row=table_row, max_row=max_row) # openpyxl bug line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 # cm 1.05*5 1.05cm = 30 pt line.width = 24 # pie.title = "Pies sold by category" line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' # line.dLbls.showCatName = True # label show line.dLbls.showVal = True # val show line.dLbls.showPercent = True # percent show # s1 = CharacterProperties(sz=1800) # font size *100 chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number + 6 * i) ws.add_chart(line, chart_cell) filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def transcribe_client_data_to_workbooks(client): report_path = r'C:\Program Files\Notepad++\reports' + '\\' + string.replace( client, '/', '-') + '_report.csv' wb = openpyxl.load_workbook( 'C:\Program Files\Notepad++\Bucket-Asset Allocation Model.xlsm', read_only=False, keep_vba=True) wb.active = 5 ws = wb.active with open(report_path, 'rU') as f: reader = csv.reader(f) for row_index, row in enumerate(reader): for column_index, cell in enumerate(row): column_letter = get_column_letter((column_index + 1)) if column_letter == 'A': if row_index > 0: ws[column_letter + str(row_index + 1)] = long( string.replace(string.replace(cell, 'Z', '9'), 'X', '0')) else: ws[column_letter + str(row_index + 1)] = cell #Proposed allocation pie chart creation #Close the file f.close() #Proposed Allocation pie chart creation wb.active = 1 ws = wb.active pie1 = PieChart() labels1 = Reference(ws, min_col=14, min_row=19, max_row=21) data1 = Reference(ws, min_col=15, min_row=18, max_row=21) pie1.add_data(data1, titles_from_data=True) pie1.set_categories(labels1) pie1.title = 'Proposed Allocation' pie1.height = 14 pie1.width = 18 ws.add_chart(pie1, "F20") pie1.dataLabels = DataLabelList() pie1.dataLabels.showPercent = True #Current allocation pie chart creation pie2 = PieChart() labels2 = Reference(ws, min_col=14, min_row=29, max_row=31) data2 = Reference(ws, min_col=15, min_row=28, max_row=31) pie2.add_data(data2, titles_from_data=True) pie2.set_categories(labels2) pie2.title = 'Current Allocation' pie2.height = 14 pie2.width = 18 ws.add_chart(pie2, 'B20') pie2.dataLabels = DataLabelList() pie2.dataLabels.showPercent = True #Bar chart creation #Change to allocations worksheet wb.active = 3 ws = wb.active #Short term bucket bar graph creation chart1 = BarChart() chart1.type = "col" chart1.style = 12 chart1.title = "Bucket I \n Short - Term" data = Reference(ws, min_col=14, min_row=61, max_row=62, max_col=15) cats = Reference(ws, min_col=13, min_row=62) chart1.add_data(data, titles_from_data=True) chart1.set_categories(cats) chart1.shape = 4 ws.add_chart(chart1, "B25") chart1.dataLabels = DataLabelList() chart1.dataLabels.showVal = True #Intermediate term bucket bar graph creation chart2 = BarChart() chart2.type = "col" chart2.style = 10 chart2.title = "Bucket II \n Intermediate - Term" data2 = Reference(ws, min_col=14, min_row=63, max_row=64, max_col=15) cats2 = Reference(ws, min_col=13, min_row=64) chart2.add_data(data2, titles_from_data=True) chart2.set_categories(cats2) chart2.shape = 4 ws.add_chart(chart2, "I25") chart2.dataLabels = DataLabelList() chart2.dataLabels.showVal = True #Long term bucket bar graph creation chart3 = BarChart() chart3.type = "col" chart3.style = 13 chart3.title = "Bucket III \n Long - Term" data3 = Reference(ws, min_col=14, min_row=65, max_row=66, max_col=15) cats3 = Reference(ws, min_col=13, min_row=66) chart3.add_data(data3, titles_from_data=True) chart3.set_categories(cats3) chart3.shape = 4 ws.add_chart(chart3, "P25") chart3.dataLabels = DataLabelList() chart3.dataLabels.showVal = True #0 portfolio bar graph creation chart4 = BarChart() chart4.type = "col" chart4.style = 10 chart4.height = 10 chart4.width = 20 chart4.title = "0 Portfolio" data4 = Reference(ws, min_col=14, min_row=57, max_row=58, max_col=15) cats4 = Reference(ws, min_col=14, min_row=57, max_col=15) chart4.add_data(data4, titles_from_data=True) chart4.set_categories(cats4) chart4.shape = 4 ws.add_chart(chart4, "B3") chart4.dataLabels = DataLabelList() chart4.dataLabels.showVal = True #Allocation Comparison Bar graph creation chart5 = BarChart() chart5.type = "col" chart5.style = 10 chart5.title = "Allocation Comparison" chart5.height = 10 chart5.width = 20 data5 = Reference(ws, min_col=10, min_row=62, max_row=64, max_col=12) cats5 = Reference(ws, min_col=9, min_row=63, max_row=64) chart5.add_data(data5, titles_from_data=True) chart5.set_categories(cats5) chart5.shape = 4 ws.add_chart(chart5, "M3") chart5.dataLabels = DataLabelList() chart5.dataLabels.showVal = True print(len(set(cdict.values()))) #Attempt to save, move on if the file is open for reading. try: wb.save('C:\\Program Files\\Notepad++\\workbooks\\' + string.replace(client, '/', '-') + '_workbook.xlsm') print(string.replace(client, '/', '-') + ' workbook completed') except IOError: print("Workbook already open, cannot overwrite, moving on.")
def create_a_report(path_load, path_save, week): workbook = xl.load_workbook( path_load, data_only=True ) # открываем базу с отчетами, data_only=True - только данные (без формул) sheet_1 = workbook.active # выбираем активный лист или sheet_1 = workbook['Отчет для АО НИПОМ'] # выбираем нужный лист wb = Workbook( ) # создаем рабочую книгу, в которую будем сохранять данные из workbook ws = wb.active # создаем рабочий лист ws.sheet_properties.tabColor = "1072BA" # задаем цвет вкладки ws.title = "Графики" # задаем имя вкладки # задаем наименование столбцов ws['A1'] = "Неделя" ws['B1'] = "Wгпэг,\nкВт*ч" ws['C1'] = "Wсм,\nкВт*ч" ws['D1'] = "Wсумм,\nкВт*ч" ws['E1'] = "Wпотр,\nкВт*ч" ws['F1'] = "Wсн,\nкВт*ч" ws['G1'] = "Моточасы\n(ГПЭГ)" ws['H1'] = "Vст (Газ),\nм^3" ws['I1'] = "Qкотла,\nкВт*ч" ws['J1'] = "Vгпэг (Газ),\nм^3" ws['K1'] = "Vкотел (Газ),\nм^3" ws['L1'] = "Vгпэг/Wсумм,\nм3/кВт*ч" ws['M1'] = "T_min,\n°C" ws['N1'] = "T_max,\n°C" ws['O1'] = "Дата начала" ws['P1'] = "Дата\nокончания" i = 2 # переменная для итерации строк в последующем цикле for # for row in range(10073, sheet_1.max_row + 1): # цикл по строкам, начиная с нужной week_OPE = [ 50, 51, 52, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 ] # количество недель ОПЭ count = 0 for row in range(5034, sheet_1.max_row + 1): # цикл по строкам с данными, начиная с 50-й недели if sheet_1.cell(row, 46).value == week_OPE[i - 2]: # если значение в ячейке # равно номеру недели из списка t_min = ws.cell( i, 13) # создаем переменную минимальной температуры АБ t_max = ws.cell( i, 14) # создаем переменную максимальной температуры АБ data_start = ws.cell(i, 15) if t_min.value is None: # проверка на наличии в ячейке значения t_min.value = 100 if t_max.value is None: # проверка на наличии в ячейке значения t_max.value = 0 if sheet_1.cell( row, 23).value < t_min.value: # проверка на меньшее значение t_min.value = sheet_1.cell(row, 23).value if sheet_1.cell( row, 23).value > t_max.value: # проверка на большее значение t_max.value = sheet_1.cell(row, 23).value if count == 0: data_start.value = sheet_1.cell(row, 3).value count = 1 if sheet_1.cell(row, 46).value == week_OPE[i - 2] and sheet_1.cell( row, 47).value == 0: # если значение в ячейке # равно номеру недели из списка и значение расхода не равно нулю v_kotel = ws.cell( i, 11 ) # создаем переменную расхода котла без учета времени работы ГПЭГ if v_kotel.value is None: # проверка на наличии в ячейке значения v_kotel.value = 0 v_kotel.value += sheet_1.cell( row, 48).value # суммирование значений в ячейках if ws.cell( i, 20).value is None: # проверка на наличии в ячейке значения ws.cell(i, 20).value = 0 ws.cell(i, 20).value += 1 # суммирование количества ячеек if sheet_1.cell( row, 1 ).value is not None: # проверяем пустая ячейка первого столбца или нет # print(sheet_1.cell(row, 1).value) week_cell = ws.cell( i, 1) # создаем переменную строк для столбца с номерами недель power_GPEG = ws.cell( i, 2 ) # создаем переменную строк для столбца с выработанной мощности ГПЭГ power_Sun = ws.cell( i, 3 ) # создаем переменную строк для столбца с выработанной мощности солнечного модуля power_Sum = ws.cell( i, 4 ) # создаем переменную строк для столбца с выработанной суммарной мощностью power_Potr = ws.cell( i, 5 ) # создаем переменную строк для столбца с потребленной нагрузкой мощностью power_SN = ws.cell( i, 6 ) # создаем переменную строк для столбца с собственными нуждами mototime_GPEG = ws.cell( i, 7) # создаем переменную строк для столбца с моточасами ГПЭГ v_Sum = ws.cell( i, 8 ) # создаем переменную строк для столбца с общим потребленным объемом газа data_end = ws.cell(i, 16) week_cell.value = sheet_1.cell( row, 1).value # присваиваем переменной значение из базовой таблицы week_cell.number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[ 1] # формат ячейки 0 power_GPEG.value = sheet_1.cell( row, 29).value # присваиваем переменной значение из базовой таблицы power_GPEG.number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[ 2] # формат ячейки 0.00 power_Sun.value = sheet_1.cell( row, 30).value # присваиваем переменной значение из базовой таблицы power_Sun.number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[ 2] # формат ячейки 0.00 power_Sum.value = sheet_1.cell( row, 31).value # присваиваем переменной значение из базовой таблицы power_Sum.number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[ 2] # формат ячейки 0.00 power_Potr.value = sheet_1.cell( row, 32).value # присваиваем переменной значение из базовой таблицы power_Potr.number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[ 2] # формат ячейки 0.00 power_SN.value = sheet_1.cell( row, 33).value # присваиваем переменной значение из базовой таблицы power_SN.number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[ 2] # формат ячейки 0.00 mototime_GPEG.value = sheet_1.cell( row, 34).value # присваиваем переменной значение из базовой таблицы mototime_GPEG.number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[ 2] # формат ячейки 0.00 v_Sum.value = sheet_1.cell( row, 35).value # присваиваем переменной значение из базовой таблицы v_Sum.number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[ 2] # формат ячейки 0.00 data_end.value = sheet_1.cell(row, 3).value count = 0 i += 1 for i in range(2, ws.max_row + 1): if ws.cell(i, 1).value is not None: ws.cell(i, 11).value = ws.cell(i, 11).value / ( ws.cell(i, 20).value / 30) * 168 # столбец с данными расхода газа котлом ws.cell( i, 11).number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[ 2] # формат ячейки 0.00 ws.cell(i, 10).value = ws.cell(i, 8).value - ws.cell( i, 11).value # столбец с данными расхода газа ГПЭГ ws.cell( i, 10).number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[ 2] # формат ячейки 0.00 ws.cell(i, 9).value = ws.cell( i, 11 ).value * 9.5 # столбец с данными выработки тепловой энергии котла ws.cell(i, 9).number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[ 1] # формат ячейки 0 ws.cell(i, 12).value = ws.cell(i, 10).value / ws.cell( i, 4 ).value # расчет эффективности выработки БКЭУ, выраженной через Vгпэг / Wсумм ws.cell( i, 12).number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[ 2] # формат ячейки 0.00 ws.cell( i, 20).value = None # удаляем временное значение количества ячеек else: ws.cell( i, 11 ).value = None # удаляем значения выходящие за пределы расчетных недель ws.cell( i, 13 ).value = None # удаляем значения выходящие за пределы расчетных недель ws.cell( i, 14 ).value = None # удаляем значения выходящие за пределы расчетных недель ws.cell( i, 15 ).value = None # удаляем значения выходящие за пределы расчетных недель ws.cell( i, 20 ).value = None # удаляем значения выходящие за пределы расчетных недель # задаем ширину столбцов ws.column_dimensions['A'].width = 10 ws.column_dimensions['B'].width = 10 ws.column_dimensions['C'].width = 10 ws.column_dimensions['D'].width = 10 ws.column_dimensions['E'].width = 10 ws.column_dimensions['F'].width = 10 ws.column_dimensions['G'].width = 12 ws.column_dimensions['H'].width = 10 ws.column_dimensions['I'].width = 10 ws.column_dimensions['J'].width = 12 ws.column_dimensions['K'].width = 14 ws.column_dimensions['L'].width = 15 ws.column_dimensions['M'].width = 10 ws.column_dimensions['N'].width = 10 ws.column_dimensions['O'].width = 18 ws.column_dimensions['P'].width = 18 thin_border = Border( # выделение границ ячеек left=Side(border_style=BORDER_THIN, color='00000000'), right=Side(border_style=BORDER_THIN, color='00000000'), top=Side(border_style=BORDER_THIN, color='00000000'), bottom=Side(border_style=BORDER_THIN, color='00000000')) # цикл для задания ячейкам заголовков свойств for row in ws.iter_cols(min_col=1, max_col=16, min_row=1, max_row=1): for cel in row: cel.font = Font(size=12, bold=True) # размер шрифта и жирное выделение cel.alignment = Alignment( horizontal="center", vertical="center", wrapText=True ) # выравнивание по центру и разрешение переноса строк cel.fill = PatternFill(start_color="EEEEEE", end_color="EEEEEE", fill_type="solid") # цикл для выделения границ ячеек for row in ws.iter_cols(min_col=1, max_col=16, min_row=1, max_row=ws.max_row): for cel in row: cel.border = thin_border # print(week) # print(ws.cell(ws.max_row-1, 1).value) if ws.cell(ws.max_row - 1, 1).value < week: return "Задана неделя вне диапазона текущего ОПЭ, равного {} недель в 2021 году".format( ws.cell(ws.max_row - 1, 1).value) # построение графиков # график "ДИАГРАММА ИЗМЕРЯЕМЫХ ПРАМЕТРОВ ПО НЕДЕЛЯМ" cats = Reference(ws, min_row=2, max_row=ws.max_row - 1, min_col=1, max_col=1) values = Reference(ws, min_row=1, max_row=ws.max_row - 1, min_col=2, max_col=8) # chart = LineChart() chart = BarChart() chart.y_axis.title = 'Параметры' chart.x_axis.title = 'Недели' chart.height = 10 chart.width = 30 chart.add_data(values, titles_from_data=True) chart.set_categories(cats) ws.add_chart(chart, "A{}".format(ws.max_row + 2)) # график выработки ГПЭГ, СМ и общий ch1 = LineChart() cats = Reference(ws, min_row=2, max_row=ws.max_row - 1, min_col=1, max_col=1) values = Reference(ws, min_row=1, max_row=ws.max_row - 1, min_col=2, max_col=4) ch1.title = "ВЫРАБОТКА ЭЛЕКТРОЭНЕРГИИ" # заголовок ch1.style = 13 # шрифт ch1.height = 10 # высота ch1.width = 20 # ширина ch1.x_axis.title = 'Недели' # подпись оси х ch1.y_axis.title = 'кВт*ч' # подпись оси у ch1.legend.position = 'r' # позиция подписей данных справа ch1.add_data( values, titles_from_data=True) # загрузка данных с заголовками столбцов ch1.set_categories(cats) # загрузка подписи оси х ch1.series[0].graphicalProperties.line.solidFill = "85C1E9" # цвет синий ch1.series[1].graphicalProperties.line.solidFill = "F7DC6F" # цвет желтый ch1.series[2].graphicalProperties.line.solidFill = "EC7063" # цвет красный ch1.series[0].graphicalProperties.solidFill = "85C1E9" # цвет синий ch1.series[1].graphicalProperties.solidFill = "F7DC6F" # цвет желтый ch1.series[2].graphicalProperties.solidFill = "EC7063" # цвет красный ws.add_chart(ch1, "A{}".format(ws.max_row + 22)) # загрузка графика в ячейку # график ПОТРЕБЛЕНИЕ ЭЛЕКТРОЭНЕРГИИ ch2 = LineChart() cats = Reference(ws, min_row=2, max_row=ws.max_row - 1, min_col=1, max_col=1) values = Reference(ws, min_row=1, max_row=ws.max_row - 1, min_col=4, max_col=6) ch2.title = "ПОТРЕБЛЕНИЕ ЭЛЕКТРОЭНЕРГИИ" # заголовок ch2.style = 13 # шрифт ch2.height = 10 # высота ch2.width = 20 # ширина ch2.x_axis.title = 'Недели' # подпись оси х ch2.y_axis.title = 'кВт*ч' # подпись оси у ch2.legend.position = 'r' # позиция подписей данных справа ch2.add_data( values, titles_from_data=True) # загрузка данных с заголовками столбцов ch2.set_categories(cats) # загрузка подписи оси х ch2.series[ 0].graphicalProperties.line.solidFill = "EC7063" # цвет линии красный ch2.series[ 1].graphicalProperties.line.solidFill = "F7DC6F" # цвет линии желтый ch2.series[ 2].graphicalProperties.line.solidFill = "85C1E9" # цвет линии синий ch2.series[ 0].graphicalProperties.solidFill = "EC7063" # цвет заливки красный ch2.series[ 1].graphicalProperties.solidFill = "F7DC6F" # цвет заливки желтый ch2.series[ 2].graphicalProperties.solidFill = "85C1E9" # цвет заливки синий ws.add_chart(ch2, "A{}".format(ws.max_row + 42)) # загрузка графика в ячейку # график ПОТРЕБЛЕНИЕ ГАЗА ch3 = LineChart() cats = Reference(ws, min_row=2, max_row=ws.max_row - 1, min_col=1, max_col=1) values = Reference(ws, min_row=1, max_row=ws.max_row - 1, min_col=10, max_col=11) ch3.title = "ПОТРЕБЛЕНИЕ ГАЗА" # заголовок ch3.style = 13 # шрифт ch3.height = 10 # высота ch3.width = 20 # ширина ch3.x_axis.title = 'Недели' # подпись оси х ch3.y_axis.title = 'м3' # подпись оси у ch3.legend.position = 'r' # позиция подписей данных справа ch3.add_data( values, titles_from_data=True) # загрузка данных с заголовками столбцов ch3.set_categories(cats) # загрузка подписи оси х ch3.series[ 0].graphicalProperties.line.solidFill = "EC7063" # цвет линии красный ch3.series[ 1].graphicalProperties.line.solidFill = "85C1E9" # цвет линии синий ch3.series[ 0].graphicalProperties.solidFill = "EC7063" # цвет заливки красный ch3.series[ 1].graphicalProperties.solidFill = "85C1E9" # цвет заливки синий ch31 = LineChart() cats = Reference(ws, min_row=2, max_row=ws.max_row - 1, min_col=1, max_col=1) values1 = Reference(ws, min_row=1, max_row=ws.max_row - 1, min_col=8, max_col=8) ch31.title = "ПОТРЕБЛЕНИЕ ГАЗА" # заголовок ch31.style = 13 # шрифт ch31.height = 10 # высота ch31.width = 20 # ширина ch31.x_axis.title = 'Недели' # подпись оси х ch31.y_axis.title = 'м3' # подпись оси у ch31.legend.position = 'r' # позиция подписей данных справа ch31.add_data( values1, titles_from_data=True) # загрузка данных с заголовками столбцов ch31.set_categories(cats) # загрузка подписи оси х ch3 += ch31 ws.add_chart(ch3, "A{}".format(ws.max_row + 62)) # загрузка графика в ячейку # график ЭФФЕКТИВНОСТЬ ВЫРАБОТКИ ЭЛЕКТРОЭНЕРГИИ БКЭУ ch4 = LineChart() cats = Reference(ws, min_row=2, max_row=ws.max_row - 1, min_col=1, max_col=1) values = Reference(ws, min_row=1, max_row=ws.max_row - 1, min_col=12, max_col=12) ch4.title = "ЭФФЕКТИВНОСТЬ ВЫРАБОТКИ ЭЛЕКТРОЭНЕРГИИ БКЭУ" # заголовок ch4.style = 13 # шрифт ch4.height = 10 # высота ch4.width = 20 # ширина ch4.x_axis.title = 'Недели' # подпись оси х ch4.y_axis.title = 'м3/кВт*ч' # подпись оси у ch4.legend.position = 'r' # позиция подписей данных справа ch4.add_data( values, titles_from_data=True) # загрузка данных с заголовками столбцов ch4.set_categories(cats) # загрузка подписи оси х ch4.series[ 0].graphicalProperties.line.solidFill = "28B463" # цвет линии зеленый ch4.series[ 0].graphicalProperties.solidFill = "28B463" # цвет заливки зеленый ws.add_chart(ch4, "A{}".format(ws.max_row + 82)) # загрузка графика в ячейку # график ВЫРАБОТКА ТЕПЛОВОЙ ЭНЕРГИИ ch5 = LineChart() cats = Reference(ws, min_row=2, max_row=ws.max_row - 1, min_col=1, max_col=1) values = Reference(ws, min_row=1, max_row=ws.max_row - 1, min_col=9, max_col=9) ch5.title = "ВЫРАБОТКА ТЕПЛОВОЙ ЭНЕРГИИ" # заголовок ch5.style = 13 # шрифт ch5.height = 10 # высота ch5.width = 20 # ширина ch5.x_axis.title = 'Недели' # подпись оси х ch5.y_axis.title = 'кВт*ч' # подпись оси у ch5.legend.position = 'r' # позиция подписей данных справа ch5.add_data( values, titles_from_data=True) # загрузка данных с заголовками столбцов ch5.set_categories(cats) # загрузка подписи оси х ch5.series[ 0].graphicalProperties.line.solidFill = "C0392B" # цвет линии красный ch5.series[ 0].graphicalProperties.solidFill = "C0392B" # цвет заливки красный ws.add_chart(ch5, "A{}".format(ws.max_row + 102)) # загрузка графика в ячейку # расчет суммы выработки ГПЭГ и СМ для построения общей диаграммы ws.cell(ws.max_row, 2).value = 0 ws.cell(ws.max_row, 3).value = 0 for i in range(2, ws.max_row + 1): if ws.cell(i, 1).value is None: ws.cell(i, 1).value = "Итого:" break if ws.cell(i, 2).value is not None: ws.cell(ws.max_row, 2).value += ws.cell(i, 2).value if ws.cell(i, 3).value is not None: ws.cell(ws.max_row, 3).value += ws.cell(i, 3).value ws.cell(ws.max_row, 3).number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[1] ws.cell(ws.max_row, 2).number_format = openpyxl.styles.numbers.BUILTIN_FORMATS[1] # построение общей диаграммы выработки ГПЭГ и СМ за отчетный период chart_itog = PieChart() labels = Reference(ws, min_col=2, max_col=3, min_row=1, max_row=1) data = Reference(ws, min_col=2, max_col=3, min_row=ws.max_row, max_row=ws.max_row) chart_itog.title = "Выработка за отчетный период {} недель".format( ws.max_row - 2) chart_itog.style = 13 # шрифт chart_itog.height = 10 # высота chart_itog.width = 20 # ширина chart_itog.add_data( data, titles_from_data=True) # загрузка данных с заголовками столбцов chart_itog.set_categories(labels) # загрузка подписи оси х slice = DataPoint(idx=0, explosion=15) # разделение пирога и сдвиг на 15 пунктов chart_itog.series[0].data_points = [ slice ] # применение сдвига к первому значению ws.add_chart(chart_itog, "A{}".format(ws.max_row + 122)) # график температур внутри блок-бокса ch6 = LineChart() cats = Reference(ws, min_row=2, max_row=ws.max_row - 1, min_col=1, max_col=1) values = Reference(ws, min_row=1, max_row=ws.max_row - 1, min_col=13, max_col=14) ch6.title = "ТЕМПЕРАТУРА ВНУТРИ БКЭУ" # заголовок ch6.style = 13 # шрифт ch6.height = 10 # высота ch6.width = 20 # ширина ch6.x_axis.title = 'Недели' # подпись оси х ch6.y_axis.title = '°C' # подпись оси у ch6.legend.position = 'r' # позиция подписей данных справа ch6.add_data( values, titles_from_data=True) # загрузка данных с заголовками столбцов ch6.set_categories(cats) # загрузка подписи оси х ch6.series[0].graphicalProperties.line.solidFill = "85C1E9" # цвет синий ch6.series[1].graphicalProperties.line.solidFill = "EC7063" # цвет красный ch6.series[0].graphicalProperties.solidFill = "85C1E9" # цвет синий ch6.series[1].graphicalProperties.solidFill = "EC7063" # цвет красный ws.add_chart(ch6, "A{}".format(ws.max_row + 142)) # загрузка графика в ячейку wb.save(path_save + '\\Графики.xlsx') # сохранение таблицы в указанную директорию # -------Генерация автоматического отчета в WORD------------------------ template = DocxTemplate('temp6707.docx') #week = 17 # задаем номер недели для отчета # задаем начальные значения недельных параметров Wfull = 0 Wcm = 0 Wgpeg = 0 Wcn = 0 Wnagr = 0 Qgvk = 0 moto = 0 Vgvk = 0 Vgpeg = 0 Vbkeu = 0 Tmin = 0 Tmax = 0 # задаем начальные значения суммы параметров за период с начала ОПЭ Wfull_sum = 0 Wcm_sum = 0 Wgpeg_sum = 0 Wcn_sum = 0 Wnagr_sum = 0 Qgvk_sum = 0 Vgvk_sum = 0 Vgpeg_sum = 0 Vbkeu_sum = 0 moto_sum = 0 # задаем начальные значения дня и месяца начала и окончания недели d_start = 0 m_start = 0 d_end = 0 m_end = 0 # рассчитываем значения за неделю и сумму с начала ОПЭ for i in range(2, ws.max_row): Wfull_sum += ws.cell(i, 4).value Wcm_sum += ws.cell(i, 3).value Wgpeg_sum += ws.cell(i, 2).value Wcn_sum += ws.cell(i, 6).value Wnagr_sum += ws.cell(i, 5).value Qgvk_sum += ws.cell(i, 9).value Vgvk_sum += ws.cell(i, 11).value Vgpeg_sum += ws.cell(i, 10).value Vbkeu_sum += ws.cell(i, 8).value moto_sum += ws.cell(i, 7).value if ws.cell(i, 1).value == week: Wfull = ws.cell(i, 4).value Wcm = ws.cell(i, 3).value Wgpeg = ws.cell(i, 2).value Wcn = ws.cell(i, 6).value Wnagr = ws.cell(i, 5).value Qgvk = ws.cell(i, 9).value moto = ws.cell(i, 7).value Vgvk = ws.cell(i, 11).value Vgpeg = ws.cell(i, 10).value Vbkeu = ws.cell(i, 8).value Tmin = ws.cell(i, 13).value Tmax = ws.cell(i, 14).value d_start = ws.cell(i, 15).value m_start = ws.cell(i, 15).value d_end = ws.cell(i, 16).value m_end = ws.cell(i, 16).value break def month_name(num): # функция возврата названия месяца по его номеру ru = [ 'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря' ] return ru[int(num) - 1] # Объявляем значения переменных, идентичных шаблону в документе word context = { 'week': week, 'year': d_end.strftime('%Y'), 'Wfull': round(Wfull, 2), 'Wcm': round(Wcm, 2), 'Wgpeg': round(Wgpeg, 2), 'Wcn': round(Wcn, 2), 'Wnagr': round(Wnagr, 2), 'Qgvk': round(Qgvk, 1), 'moto': moto, 'Vgvk': round(Vgvk, 2), 'Vgpeg': round(Vgpeg, 2), 'Vbkeu': round(Vbkeu, 2), 'Tmin': Tmin, 'Tmax': Tmax, 'Wfull_sum': round(Wfull_sum, 1), 'Wcm_sum': round(Wcm_sum, 1), 'Wgpeg_sum': round(Wgpeg_sum, 1), 'Wcn_sum': round(Wcn_sum, 1), 'Wnagr_sum': round(Wnagr_sum, 1), 'Qgvk_sum': round(Qgvk_sum), 'Vgvk_sum': round(Vgvk_sum, 1), 'Vgpeg_sum': round(Vgpeg_sum, 1), 'Vbkeu_sum': round(Vbkeu_sum, 1), 'moto_sum': moto_sum, 'd_start': d_start.strftime('%d'), 'm_start': month_name(m_start.strftime('%m')), 'd_end': d_end.strftime('%d'), 'm_end': month_name(m_end.strftime('%m')) } # создаем автоматизированный отчет template.render(context) template.save(path_save + '\\Еженедельный отчет по ОПЭ БКЭУ-{}.docx'.format(week) ) # сохранение отчета с атоприсвоением номера недели file_path = path_save + '\\Еженедельный отчет по ОПЭ БКЭУ-{}.docx'.format( week) os.startfile(file_path) return "Отчет успешно сформирован"
def create_spreadsheet(base_channel_report): # Setup Excel file filename = "server_os_report.xlsx" workbook = Workbook() ws1 = workbook.create_sheet("Sheet_A") ws1.title = "Overview Linux OS" ws2 = workbook.create_sheet("Sheet_B") ws2.title = "Data" ws3 = workbook.create_sheet("Sheet_C") ws3.title = "Approver Breakdown" sheet = workbook["Data"] for row in base_channel_report: sheet.append(row) darkyellow_background = PatternFill(bgColor=colors.DARKYELLOW) yellow_background = PatternFill(bgColor=colors.YELLOW) blue_background = PatternFill(bgColor=colors.BLUE) green_background = PatternFill(bgColor=colors.GREEN) diff_style7 = DifferentialStyle(fill=darkyellow_background) rule7 = Rule(type="expression", dxf=diff_style7) rule7.formula = ["$C1=7"] sheet.conditional_formatting.add("A1:E600", rule7) diff_style8 = DifferentialStyle(fill=blue_background) rule8 = Rule(type="expression", dxf=diff_style8) rule8.formula = ["$C1=7"] sheet.conditional_formatting.add("A1:E600", rule8) diff_style6 = DifferentialStyle(fill=yellow_background) rule6 = Rule(type="expression", dxf=diff_style6) rule6.formula = ["$C1=6"] sheet.conditional_formatting.add("A1:E600", rule6) diff_style5 = DifferentialStyle(fill=green_background) rule5 = Rule(type="expression", dxf=diff_style5) rule5.formula = ["$C1=5"] sheet.conditional_formatting.add("A1:E600", rule5) sheet = workbook["Overview Linux OS"] data = [ ['Centos5', '=COUNTIFS(Data!$C$2:$C$600,5, Data!$B$2:$B$600,"Centos")'], ['Centos6', '=COUNTIFS(Data!$C$2:$C$600,6, Data!$B$2:$B$600,"Centos")'], ['Centos7', '=COUNTIFS(Data!$C$2:$C$600,7, Data!$B$2:$B$600,"Centos")'], ['Centos8', '=COUNTIFS(Data!$C$2:$C$600,8, Data!$B$2:$B$600,"Centos")'], ['RedHat5', '=COUNTIFS(Data!$C$2:$C$600,5, Data!$B$2:$B$600,"Redhat")'], ['RedHat6', '=COUNTIFS(Data!$C$2:$C$600,6, Data!$B$2:$B$600,"Redhat")'], ['RedHat7', '=COUNTIFS(Data!$C$2:$C$600,7, Data!$B$2:$B$600,"Redhat")'], ['RedHat8', '=COUNTIFS(Data!$C$2:$C$600,8, Data!$B$2:$B$600,"Redhat")'], ['Unknown', '=COUNTIFS(Data!$C$2:$C$600,0)'] ] for row in data: sheet.append(row) pie = PieChart() labels = Reference(sheet, min_col=1, min_row=2, max_row=9) data = Reference(sheet, min_col=2, min_row=1, max_row=9) pie.add_data(data, titles_from_data=True) pie.set_categories(labels) pie.title = "OS Breakdown" pie.height = 20 pie.width = 40 # Cut the first slice out of the pie slice = DataPoint(idx=0, explosion=20) pie.series[0].data_points = [slice] sheet.add_chart(pie, "A1") std=workbook.get_sheet_by_name('Sheet') workbook.remove_sheet(std) unique_cost_center = set(x for l in base_channel_report for x in l) ws3 = workbook.create_sheet("Sheet_C") ws3.title = "Cost Center Breakdown" sheet = workbook["Cost Centre Breakdown"] data =[] for x in unique_cost_center: countifs = "=COUNTIFS(Data!$H$2:$H$600,%s)" % x data.append([x,countifs]) for row in data: sheet.append(row) pie = PieChart() labels = Reference(sheet, min_col=1, min_row=2, max_row=len(data)) data = Reference(sheet, min_col=2, min_row=1, max_row=len(data)) pie.add_data(data, titles_from_data=True) pie.set_categories(labels) pie.title = "Cost Center Breakdown" pie.height = 20 pie.width = 40 # Cut the first slice out of the pie slice = DataPoint(idx=0, explosion=20) pie.series[0].data_points = [slice] sheet.add_chart(pie, "A1") # save file workbook.save(filename)
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active # Row height ws.row_dimensions[1].height = 102 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 42 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('L')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Constantia', size=15, bold=True) title_font = Font(name='宋体', size=15, bold=True) data_font = Font(name='Franklin Gothic Book', size=11) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000')) b_border = Border(bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_r_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") img.width = img.width * 0.85 img.height = img.height * 0.85 # img = Image("myems.png") ws.add_image(img, 'B1') # Title ws.row_dimensions[3].height = 60 ws['B3'].font = name_font ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'].font = name_font ws['C3'] = name ws['D3'].font = name_font ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'].font = name_font ws['E3'] = period_type ws['F3'].font = name_font ws['F3'].alignment = b_r_alignment ws['F3'] = 'Date:' ws['G3'].border = b_border ws['G3'].alignment = b_c_alignment ws['G3'].font = name_font ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local ws.merge_cells("G3:H3") if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename ################################## current_row_number = 6 reporting_period_data = report['reporting_period'] has_names_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_names_data_flag = False if has_names_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 报告期产出' current_row_number += 1 category = reporting_period_data['names'] ca_len = len(category) ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].border = f_border col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '产出' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '单位面积值' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round( reporting_period_data['subtotals_per_unit_area'][i], 2) col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '环比' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = str( round(reporting_period_data['increment_rates'][i] * 100, 2)) + '%' \ if reporting_period_data['increment_rates'][i] is not None else '-' col = chr(ord(col) + 1) current_row_number += 2 ####################### has_values_data = True has_timestamps_data = True if 'values' not in reporting_period_data.keys() or \ reporting_period_data['values'] is None or \ len(reporting_period_data['values']) == 0: has_values_data = False if 'timestamps' not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0 or \ len(reporting_period_data['timestamps'][0]) == 0: has_timestamps_data = False if has_values_data and has_timestamps_data: ca_len = len(reporting_period_data['names']) time = reporting_period_data['timestamps'][0] real_timestamps_len = timestamps_data_not_equal_0( report['parameters']['timestamps']) ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 详细数据' current_row_number += 1 chart_start_row_number = current_row_number current_row_number += ca_len * 6 + real_timestamps_len * 7 + 1 table_start_row_number = current_row_number ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '日期时间' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" col = chr(ord(col) + 1) current_row_number += 1 for i in range(0, len(time)): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = time[i] col = 'C' for j in range(0, ca_len): ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['values'][j][i], 2) \ if reporting_period_data['values'][j][i] is not None else 0.00 col = chr(ord(col) + 1) current_row_number += 1 table_end_row_number = current_row_number - 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '小计' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) col = chr(ord(col) + 1) current_row_number += 2 format_time_width_number = 1.0 min_len_number = 1.0 min_width_number = 11.0 # format_time_width_number * min_len_number + 4 and min_width_number > 11.0 if period_type == 'hourly': format_time_width_number = 4.0 min_len_number = 2 min_width_number = 12.0 elif period_type == 'daily': format_time_width_number = 2.5 min_len_number = 4 min_width_number = 14.0 elif period_type == 'monthly': format_time_width_number = 2.1 min_len_number = 4 min_width_number = 12.4 elif period_type == 'yearly': format_time_width_number = 1.5 min_len_number = 5 min_width_number = 11.5 for i in range(0, ca_len): line = LineChart() line.title = '报告期产出 - ' + \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) line_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = format_time_width_number * len(time) if len( time) > min_len_number else min_width_number if line.width > 24: line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = True line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number) chart_start_row_number += 6 ws.add_chart(line, chart_cell) ##################################### has_child_flag = True if "child_space" not in report.keys() or "energy_category_names" not in report['child_space'].keys() or \ len(report['child_space']["energy_category_names"]) == 0 \ or 'child_space_names_array' not in report['child_space'].keys() \ or report['child_space']['child_space_names_array'] is None \ or len(report['child_space']['child_space_names_array']) == 0 \ or len(report['child_space']['child_space_names_array'][0]) == 0: has_child_flag = False if has_child_flag: child = report['child_space'] ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 子空间数据' current_row_number += 1 table_start_row_number = current_row_number ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].border = f_border ca_len = len(child['energy_category_names']) for i in range(0, ca_len): row = chr(ord('C') + i) ws[row + str(current_row_number)].fill = table_fill ws[row + str(current_row_number)].font = name_font ws[row + str(current_row_number)].alignment = c_c_alignment ws[row + str(current_row_number)].border = f_border ws[row + str(current_row_number)] = \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" space_len = len(child['child_space_names_array'][0]) for i in range(0, space_len): current_row_number += 1 row = str(current_row_number) ws['B' + row].font = name_font ws['B' + row].alignment = c_c_alignment ws['B' + row] = child['child_space_names_array'][0][i] ws['B' + row].border = f_border for j in range(0, ca_len): col = chr(ord('C') + j) ws[col + row].font = name_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(child['subtotals_array'][j][i], 2) ws[col + row].border = f_border table_end_row_number = current_row_number current_row_number += 1 pie_start_row_number = current_row_number # Pie for i in range(0, ca_len): pie = PieChart() labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 6.6 pie.width = 8 pie.title = ws.cell(column=3 + i, row=table_start_row_number).value s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True chart_cell = '' if i % 2 == 0: chart_cell = 'B' + str(pie_start_row_number) else: chart_cell = 'E' + str(pie_start_row_number) pie_start_row_number += 5 ws.add_chart(pie, chart_cell) current_row_number = pie_start_row_number if ca_len % 2 == 1: current_row_number += 5 current_row_number += 1 ########################################## current_sheet_parameters_row_number = chart_start_row_number + 1 has_parameters_names_and_timestamps_and_values_data = True if 'parameters' not in report.keys() or \ report['parameters'] is None or \ 'names' not in report['parameters'].keys() or \ report['parameters']['names'] is None or \ len(report['parameters']['names']) == 0 or \ 'timestamps' not in report['parameters'].keys() or \ report['parameters']['timestamps'] is None or \ len(report['parameters']['timestamps']) == 0 or \ 'values' not in report['parameters'].keys() or \ report['parameters']['values'] is None or \ len(report['parameters']['values']) == 0 or \ timestamps_data_all_equal_0(report['parameters']['timestamps']): has_parameters_names_and_timestamps_and_values_data = False if has_parameters_names_and_timestamps_and_values_data: ############################### # new worksheet ############################### parameters_data = report['parameters'] parameters_names_len = len(parameters_data['names']) parameters_ws = wb.create_sheet('相关参数') parameters_timestamps_data_max_len = \ get_parameters_timestamps_lists_max_len(list(parameters_data['timestamps'])) # Row height parameters_ws.row_dimensions[1].height = 102 for i in range(2, 7 + 1): parameters_ws.row_dimensions[i].height = 42 for i in range(8, parameters_timestamps_data_max_len + 10): parameters_ws.row_dimensions[i].height = 60 # Col width parameters_ws.column_dimensions['A'].width = 1.5 parameters_ws.column_dimensions['B'].width = 25.0 for i in range(3, 12 + parameters_names_len * 3): parameters_ws.column_dimensions[format_cell.get_column_letter( i)].width = 15.0 # Img img = Image("excelexporters/myems.png") img.width = img.width * 0.85 img.height = img.height * 0.85 # img = Image("myems.png") parameters_ws.add_image(img, 'B1') # Title parameters_ws.row_dimensions[3].height = 60 parameters_ws['B3'].font = name_font parameters_ws['B3'].alignment = b_r_alignment parameters_ws['B3'] = 'Name:' parameters_ws['C3'].border = b_border parameters_ws['C3'].alignment = b_c_alignment parameters_ws['C3'].font = name_font parameters_ws['C3'] = name parameters_ws['D3'].font = name_font parameters_ws['D3'].alignment = b_r_alignment parameters_ws['D3'] = 'Period:' parameters_ws['E3'].border = b_border parameters_ws['E3'].alignment = b_c_alignment parameters_ws['E3'].font = name_font parameters_ws['E3'] = period_type parameters_ws['F3'].font = name_font parameters_ws['F3'].alignment = b_r_alignment parameters_ws['F3'] = 'Date:' parameters_ws['G3'].border = b_border parameters_ws['G3'].alignment = b_c_alignment parameters_ws['G3'].font = name_font parameters_ws[ 'G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local parameters_ws.merge_cells("G3:H3") parameters_ws_current_row_number = 6 parameters_ws['B' + str(parameters_ws_current_row_number)].font = title_font parameters_ws['B' + str(parameters_ws_current_row_number)] = name + ' 相关参数' parameters_ws_current_row_number += 1 parameters_table_start_row_number = parameters_ws_current_row_number parameters_ws.row_dimensions[ parameters_ws_current_row_number].height = 80 parameters_ws_current_row_number += 1 table_current_col_number = 2 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border parameters_ws[col + str(parameters_ws_current_row_number - 1)].font = name_font parameters_ws[col + str(parameters_ws_current_row_number - 1)].alignment = c_c_alignment parameters_ws[col + str(parameters_ws_current_row_number - 1)] = parameters_data['names'][i] table_current_row_number = parameters_ws_current_row_number for j, value in enumerate(list(parameters_data['timestamps'][i])): col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = value col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = round( parameters_data['values'][i][j], 2) table_current_row_number += 1 table_current_col_number = table_current_col_number + 3 ######################################################## # parameters chart and parameters table ######################################################## ws['B' + str(current_sheet_parameters_row_number)].font = title_font ws['B' + str(current_sheet_parameters_row_number)] = name + ' 相关参数' current_sheet_parameters_row_number += 1 chart_start_row_number = current_sheet_parameters_row_number col_index = 0 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue line = LineChart() data_col = 3 + col_index * 3 labels_col = 2 + col_index * 3 col_index += 1 line.title = '相关参数 - ' + \ parameters_ws.cell(row=parameters_table_start_row_number, column=data_col).value labels = Reference(parameters_ws, min_col=labels_col, min_row=parameters_table_start_row_number + 1, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line_data = Reference( parameters_ws, min_col=data_col, min_row=parameters_table_start_row_number, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = False line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number) chart_start_row_number += 6 ws.add_chart(line, chart_cell) current_sheet_parameters_row_number = chart_start_row_number current_sheet_parameters_row_number += 1 ########################################## filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active # Row height ws.row_dimensions[1].height = 118 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 30 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('I')): ws.column_dimensions[chr(i)].width = 25.0 # Font name_font = Font(name='Constantia', size=15, bold=True) name_small_font = Font(name='Constantia', size=10, bold=True) title_font = Font(name='宋体', size=15, bold=True) title_small_font = Font(name='宋体', size=10, bold=True) data_font = Font(name='Franklin Gothic Book', size=11) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000') ) b_border = Border( bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) c_r_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=False, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") # img = Image("myems.png") ws.add_image(img, 'B1') # Title ws['B3'].font = name_font ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'].font = name_font ws['C3'] = name ws['D3'].font = name_font ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'].font = name_font ws['E3'] = period_type ws['F3'].font = name_font ws['F3'].alignment = b_r_alignment ws['F3'] = 'Date:' ws.merge_cells("G3:J3") for i in range(ord('G'), ord('K')): ws[chr(i) + '3'].border = b_border ws['G3'].alignment = b_c_alignment ws['G3'].font = name_font ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename ################################## current_row_number = 6 reporting_period_data = report['reporting_period'] has_names_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_names_data_flag = False if has_names_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 报告期节约' current_row_number += 1 category = reporting_period_data['names'] ca_len = len(category) ws['B' + str(current_row_number)].fill = table_fill col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = name_small_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = \ reporting_period_data['names'][i] + " (基线-实际) (" + reporting_period_data['units'][i] + ")" col = chr(ord(col) + 1) ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = name_small_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = '吨标准煤 (基线-实际) (TCE)' col = chr(ord(col) + 1) ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = name_small_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = '吨二氧化碳排放 (基线-实际) (TCO2E)' col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '节约' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['subtotals_saving'][i], 2) col = chr(ord(col) + 1) ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['total_in_kgce_saving'], 2) col = chr(ord(col) + 1) ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['total_in_kgco2e_saving'], 2) col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '单位面积值' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['subtotals_per_unit_area_saving'][i], 2) col = chr(ord(col) + 1) ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['total_in_kgco2e_per_unit_area_saving'], 2) col = chr(ord(col) + 1) ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['total_in_kgce_per_unit_area_saving'], 2) col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '环比' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = str( round(reporting_period_data['increment_rates_saving'][i] * 100, 2)) + '%' \ if reporting_period_data['increment_rates_saving'][i] is not None else '-' col = chr(ord(col) + 1) ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = str( round(reporting_period_data['increment_rate_in_kgce_saving'] * 100, 2)) + '%' \ if reporting_period_data['increment_rate_in_kgce_saving'] is not None else '-' col = chr(ord(col) + 1) ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = str( round(reporting_period_data['increment_rate_in_kgco2e_saving'] * 100, 2)) + '%' \ if reporting_period_data['increment_rate_in_kgco2e_saving'] is not None else '-' col = chr(ord(col) + 1) current_row_number += 2 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 吨标准煤(TCE)占比' current_row_number += 1 table_start_row_number = current_row_number chart_start_row_number = current_row_number ws['B' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].font = name_small_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = '吨标准煤(TCE)占比' current_row_number += 1 for i in range(0, ca_len): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = reporting_period_data['names'][i] ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round(reporting_period_data['subtotals_in_kgce_saving'][i], 2) current_row_number += 1 table_end_row_number = current_row_number - 1 if ca_len < 4: current_row_number = current_row_number - ca_len + 4 current_row_number += 1 pie = PieChart() pie.title = '吨标准煤(TCE)占比' labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 5.25 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True ws.add_chart(pie, 'D' + str(chart_start_row_number)) ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 吨二氧化碳排放(TCO2E)占比' current_row_number += 1 table_start_row_number = current_row_number chart_start_row_number = current_row_number ws['B' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].font = name_small_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = '吨二氧化碳排放(TCO2E)占比' current_row_number += 1 for i in range(0, ca_len): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = reporting_period_data['names'][i] ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round(reporting_period_data['subtotals_in_kgco2e_saving'][i], 2) current_row_number += 1 table_end_row_number = current_row_number - 1 if ca_len < 4: current_row_number = current_row_number - ca_len + 4 current_row_number += 1 pie = PieChart() pie.title = '吨二氧化碳排放(TCO2E)占比' labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 5.25 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True ws.add_chart(pie, 'D' + str(chart_start_row_number)) ############################################# has_values_saving_data = True has_timestamps_data = True if 'values_saving' not in reporting_period_data.keys() or \ reporting_period_data['values_saving'] is None or \ len(reporting_period_data['values_saving']) == 0: has_values_saving_data = False if 'timestamps' not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0 or \ len(reporting_period_data['timestamps'][0]) == 0: has_timestamps_data = False if has_values_saving_data and has_timestamps_data: ca_len = len(reporting_period_data['names']) time = reporting_period_data['timestamps'][0] ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 详细数据' current_row_number += 1 chart_start_row_number = current_row_number current_row_number += ca_len * 5 table_start_row_number = current_row_number ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '日期时间' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" col = chr(ord(col) + 1) current_row_number += 1 for i in range(0, len(time)): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = time[i] col = 'C' for j in range(0, ca_len): ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['values_saving'][j][i], 2) \ if reporting_period_data['values_saving'][j][i] is not None else 0.00 col = chr(ord(col) + 1) current_row_number += 1 table_end_row_number = current_row_number - 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = '小计' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['subtotals_saving'][i], 2) col = chr(ord(col) + 1) current_row_number += 2 format_time_width_number = 1.0 min_len_number = 1.0 min_width_number = 11.0 # format_time_width_number * min_len_number + 4 and min_width_number > 11.0 if period_type == 'hourly': format_time_width_number = 4.0 min_len_number = 2 min_width_number = 12.0 elif period_type == 'daily': format_time_width_number = 2.5 min_len_number = 4 min_width_number = 14.0 elif period_type == 'monthly': format_time_width_number = 2.1 min_len_number = 4 min_width_number = 12.4 elif period_type == 'yearly': format_time_width_number = 1.5 min_len_number = 5 min_width_number = 11.5 for i in range(0, ca_len): bar = BarChart() bar.title = \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) bar_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number) bar.add_data(bar_data, titles_from_data=True) bar.set_categories(labels) bar.height = 5.25 bar.width = format_time_width_number * len(time) if len(time) > min_len_number else min_width_number bar.dLbls = DataLabelList() bar.dLbls.showVal = True bar.dLbls.showPercent = True chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number) chart_start_row_number += 5 ws.add_chart(bar, chart_cell) filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active ws.title = "StoreEnergyCategory" # Row height ws.row_dimensions[1].height = 102 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 42 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('L')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Arial', size=15, bold=True) title_font = Font(name='Arial', size=15, bold=True) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000') ) b_border = Border( bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") ws.add_image(img, 'A1') # Title ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'] = name ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'] = period_type ws['B4'].alignment = b_r_alignment ws['B4'] = 'Reporting Start Datetime:' ws['C4'].border = b_border ws['C4'].alignment = b_c_alignment ws['C4'] = reporting_start_datetime_local ws['D4'].alignment = b_r_alignment ws['D4'] = 'Reporting End Datetime:' ws['E4'].border = b_border ws['E4'].alignment = b_c_alignment ws['E4'] = reporting_end_datetime_local if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename #################################################################################################################### # First: Consumption # 6: title # 7: table title # 8~10 table_data # Total: 5 rows # if has not energy data: set low height for rows #################################################################################################################### reporting_period_data = report['reporting_period'] has_energy_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_energy_data_flag = False if has_energy_data_flag: ws['B6'].font = title_font ws['B6'] = name + ' ' + 'Consumption' category = reporting_period_data['names'] ca_len = len(category) ws.row_dimensions[7].height = 60 ws['B7'].fill = table_fill ws['B7'].border = f_border ws['B8'].font = title_font ws['B8'].alignment = c_c_alignment ws['B8'] = 'Consumption' ws['B8'].border = f_border ws['B9'].font = title_font ws['B9'].alignment = c_c_alignment ws['B9'] = 'Per Unit Area' ws['B9'].border = f_border ws['B10'].font = title_font ws['B10'].alignment = c_c_alignment ws['B10'] = 'Increment Rate' ws['B10'].border = f_border col = '' for i in range(0, ca_len): col = chr(ord('C') + i) row = '7' cell = col + row ws[col + '7'].fill = table_fill ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = round(reporting_period_data['subtotals'][i], 2) ws[col + '8'].border = f_border ws[col + '9'].font = name_font ws[col + '9'].alignment = c_c_alignment ws[col + '9'] = round(reporting_period_data['subtotals_per_unit_area'][i], 2) ws[col + '9'].border = f_border ws[col + '10'].font = name_font ws[col + '10'].alignment = c_c_alignment ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \ if reporting_period_data['increment_rates'][i] is not None else "-" ws[col + '10'].border = f_border # TCE TCO2E end_col = col # TCE tce_col = chr(ord(end_col) + 1) ws[tce_col + '7'].fill = table_fill ws[tce_col + '7'].font = name_font ws[tce_col + '7'].alignment = c_c_alignment ws[tce_col + '7'] = 'Ton of Standard Coal (TCE)' ws[tce_col + '7'].border = f_border ws[tce_col + '8'].font = name_font ws[tce_col + '8'].alignment = c_c_alignment ws[tce_col + '8'] = round(reporting_period_data['total_in_kgce'] / 1000, 2) ws[tce_col + '8'].border = f_border ws[tce_col + '9'].font = name_font ws[tce_col + '9'].alignment = c_c_alignment ws[tce_col + '9'] = round(reporting_period_data['total_in_kgce_per_unit_area'] / 1000, 2) ws[tce_col + '9'].border = f_border ws[tce_col + '10'].font = name_font ws[tce_col + '10'].alignment = c_c_alignment ws[tce_col + '10'] = str(round(reporting_period_data['increment_rate_in_kgce'] * 100, 2)) + "%" \ if reporting_period_data['increment_rate_in_kgce'] is not None else "-" ws[tce_col + '10'].border = f_border # TCO2E tco2e_col = chr(ord(end_col) + 2) ws[tco2e_col + '7'].fill = table_fill ws[tco2e_col + '7'].font = name_font ws[tco2e_col + '7'].alignment = c_c_alignment ws[tco2e_col + '7'] = 'Ton of Carbon Dioxide Emissions (TCO2E)' ws[tco2e_col + '7'].border = f_border ws[tco2e_col + '8'].font = name_font ws[tco2e_col + '8'].alignment = c_c_alignment ws[tco2e_col + '8'] = round(reporting_period_data['total_in_kgco2e'] / 1000, 2) ws[tco2e_col + '8'].border = f_border ws[tco2e_col + '9'].font = name_font ws[tco2e_col + '9'].alignment = c_c_alignment ws[tco2e_col + '9'] = round(reporting_period_data['total_in_kgco2e_per_unit_area'] / 1000, 2) ws[tco2e_col + '9'].border = f_border ws[tco2e_col + '10'].font = name_font ws[tco2e_col + '10'].alignment = c_c_alignment ws[tco2e_col + '10'] = str(round(reporting_period_data['increment_rate_in_kgco2e'] * 100, 2)) + "%" \ if reporting_period_data['increment_rate_in_kgco2e'] is not None else "-" ws[tco2e_col + '10'].border = f_border else: for i in range(6, 10 + 1): ws.row_dimensions[i].height = 0.1 #################################################################################################################### # Second: Electricity Consumption by Time-Of-Use # 12: title # 13: table title # 14~17 table_data # Total: 6 rows #################################################################################################################### has_ele_peak_flag = True if "toppeaks" not in reporting_period_data.keys() or \ reporting_period_data['toppeaks'] is None or \ len(reporting_period_data['toppeaks']) == 0: has_ele_peak_flag = False if has_ele_peak_flag: ws['B12'].font = title_font ws['B12'] = name + ' ' + 'Electricity Consumption by Time-Of-Use' ws.row_dimensions[13].height = 60 ws['B13'].fill = table_fill ws['B13'].font = name_font ws['B13'].alignment = c_c_alignment ws['B13'].border = f_border ws['C13'].fill = table_fill ws['C13'].font = name_font ws['C13'].alignment = c_c_alignment ws['C13'].border = f_border ws['C13'] = 'Electricity Consumption by Time-Of-Use' ws['B14'].font = title_font ws['B14'].alignment = c_c_alignment ws['B14'] = 'TopPeak' ws['B14'].border = f_border ws['C14'].font = title_font ws['C14'].alignment = c_c_alignment ws['C14'].border = f_border ws['C14'] = round(reporting_period_data['toppeaks'][0], 2) ws['B15'].font = title_font ws['B15'].alignment = c_c_alignment ws['B15'] = 'OnPeak' ws['B15'].border = f_border ws['C15'].font = title_font ws['C15'].alignment = c_c_alignment ws['C15'].border = f_border ws['C15'] = round(reporting_period_data['onpeaks'][0], 2) ws['B16'].font = title_font ws['B16'].alignment = c_c_alignment ws['B16'] = 'MidPeak' ws['B16'].border = f_border ws['C16'].font = title_font ws['C16'].alignment = c_c_alignment ws['C16'].border = f_border ws['C16'] = round(reporting_period_data['midpeaks'][0], 2) ws['B17'].font = title_font ws['B17'].alignment = c_c_alignment ws['B17'] = 'OffPeak' ws['B17'].border = f_border ws['C17'].font = title_font ws['C17'].alignment = c_c_alignment ws['C17'].border = f_border ws['C17'] = round(reporting_period_data['offpeaks'][0], 2) pie = PieChart() pie.title = name + ' ' + 'Electricity Consumption by Time-Of-Use' labels = Reference(ws, min_col=2, min_row=14, max_row=17) pie_data = Reference(ws, min_col=3, min_row=13, max_row=17) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 7.25 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False # 标签显示 s1.dLbls.showVal = True # 数量显示 s1.dLbls.showPercent = True # 百分比显示 ws.add_chart(pie, "D13") else: for i in range(12, 18 + 1): ws.row_dimensions[i].height = 0.1 #################################################################################################################### # Third: Ton of Standard Coal(TCE) by Energy Category # current_row_number: title # current_row_number + 1: table title # current_row_number + 1 + ca_len table_data # Total: 2 + ca_len rows #################################################################################################################### current_row_number = 19 has_kgce_data_flag = True if "subtotals_in_kgce" not in reporting_period_data.keys() or \ reporting_period_data['subtotals_in_kgce'] is None or \ len(reporting_period_data['subtotals_in_kgce']) == 0: has_kgce_data_flag = False if has_kgce_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + 'Ton of Standard Coal(TCE) by Energy Category' current_row_number += 1 table_start_row_number = current_row_number ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = name_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = 'Ton of Standard Coal(TCE) by Energy Category' current_row_number += 1 ca_len = len(reporting_period_data['names']) for i in range(0, ca_len): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = reporting_period_data['names'][i] ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].font = title_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round(reporting_period_data['subtotals_in_kgce'][i] / 1000, 3) current_row_number += 1 table_end_row_number = current_row_number - 1 pie = PieChart() pie.title = name + ' ' + ws.cell(column=3, row=table_start_row_number).value labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 7.25 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True table_cell = 'D' + str(table_start_row_number) ws.add_chart(pie, table_cell) if ca_len < 4: current_row_number = current_row_number - ca_len + 4 current_row_number += 1 #################################################################################################################### # Fourth: Ton of Carbon Dioxide Emissions(TCO2E) by Energy Category # current_row_number: title # current_row_number + 1: table title # current_row_number + 1 + ca_len table_data # Total: 2 + ca_len rows #################################################################################################################### has_kgco2e_data_flag = True if "subtotals_in_kgco2e" not in reporting_period_data.keys() or \ reporting_period_data['subtotals_in_kgco2e'] is None or \ len(reporting_period_data['subtotals_in_kgco2e']) == 0: has_kgco2e_data_flag = False if has_kgco2e_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + 'Ton of Carbon Dioxide Emissions(TCO2E) by Energy Category' current_row_number += 1 table_start_row_number = current_row_number ws.row_dimensions[current_row_number].height = 75 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = name_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = 'Ton of Carbon Dioxide Emissions(TCO2E) by Energy Category' current_row_number += 1 ca_len = len(reporting_period_data['names']) for i in range(0, ca_len): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = reporting_period_data['names'][i] ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].font = title_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round(reporting_period_data['subtotals_in_kgco2e'][i] / 1000, 3) current_row_number += 1 table_end_row_number = current_row_number - 1 pie = PieChart() pie.title = name + ' ' + ws.cell(column=3, row=table_start_row_number).value labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 7.75 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True table_cell = 'D' + str(table_start_row_number) ws.add_chart(pie, table_cell) if ca_len < 4: current_row_number = current_row_number - ca_len + 4 current_row_number += 1 #################################################################################################################### # Fifth: Detailed Data # current_row_number: title # current_row_number+1 ~ current_row_number+1+ca_len*6-1: line # current_row_number+1+ca_len*6: table title # current_row_number+1+ca_len*6~: table_data #################################################################################################################### reporting_period_data = report['reporting_period'] times = reporting_period_data['timestamps'] has_detail_data_flag = True ca_len = len(report['reporting_period']['names']) parameters_names_len = len(report['parameters']['names']) parameters_parameters_datas_len = 0 for i in range(0, parameters_names_len): if len(report['parameters']['timestamps'][i]) == 0: continue parameters_parameters_datas_len += 1 table_row = current_row_number + (ca_len + parameters_parameters_datas_len) * 6 + 2 chart_start_row_number = current_row_number + 1 if "timestamps" not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0: has_detail_data_flag = False if has_detail_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + 'Detailed Data' ws.row_dimensions[table_row].height = 60 ws['B'+str(table_row)].fill = table_fill ws['B' + str(table_row)].font = title_font ws['B'+str(table_row)].border = f_border ws['B'+str(table_row)].alignment = c_c_alignment ws['B'+str(table_row)] = 'Datetime' time = times[0] has_data = False max_row = 0 if len(time) > 0: has_data = True max_row = table_row + len(time) if has_data: for i in range(0, len(time)): col = 'B' row = str(table_row+1 + i) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = time[i] ws[col + row].border = f_border for i in range(0, ca_len): # 38 title col = chr(ord('C') + i) ws[col + str(table_row)].fill = table_fill ws[col + str(table_row)].font = title_font ws[col + str(table_row)].alignment = c_c_alignment ws[col + str(table_row)] = reporting_period_data['names'][i] + \ " (" + reporting_period_data['units'][i] + ")" ws[col + str(table_row)].border = f_border # 39 data time = times[i] time_len = len(time) for j in range(0, time_len): row = str(table_row+1 + j) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(reporting_period_data['values'][i][j], 2) ws[col + row].border = f_border current_row_number = table_row + 1 + len(times[0]) ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = 'Subtotal' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 2) # line # 39~: line line = LineChart() line.title = 'Reporting Period Consumption - ' + ws.cell(column=3+i, row=table_row).value labels = Reference(ws, min_col=2, min_row=table_row+1, max_row=max_row) line_data = Reference(ws, min_col=3 + i, min_row=table_row, max_row=max_row) # openpyxl bug line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = True # val show line.dLbls.showPercent = True # percent show chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number + 6*i) ws.add_chart(line, chart_cell) ########################################## has_parameters_names_and_timestamps_and_values_data = True # 12 is the starting line number of the last line chart in the report period ca_len = len(report['reporting_period']['names']) current_sheet_parameters_row_number = chart_start_row_number + ca_len * 6 if 'parameters' not in report.keys() or \ report['parameters'] is None or \ 'names' not in report['parameters'].keys() or \ report['parameters']['names'] is None or \ len(report['parameters']['names']) == 0 or \ 'timestamps' not in report['parameters'].keys() or \ report['parameters']['timestamps'] is None or \ len(report['parameters']['timestamps']) == 0 or \ 'values' not in report['parameters'].keys() or \ report['parameters']['values'] is None or \ len(report['parameters']['values']) == 0 or \ timestamps_data_all_equal_0(report['parameters']['timestamps']): has_parameters_names_and_timestamps_and_values_data = False if has_parameters_names_and_timestamps_and_values_data: ################################################################################################################ # new worksheet ################################################################################################################ parameters_data = report['parameters'] parameters_names_len = len(parameters_data['names']) file_name = "Store"+re.sub(r'[^A-Z]', '', ws.title.strip('S')) + "_" parameters_ws = wb.create_sheet(file_name + 'Parameters') parameters_timestamps_data_max_len = \ get_parameters_timestamps_lists_max_len(list(parameters_data['timestamps'])) # Row height parameters_ws.row_dimensions[1].height = 102 for i in range(2, 7 + 1): parameters_ws.row_dimensions[i].height = 42 for i in range(8, parameters_timestamps_data_max_len + 10): parameters_ws.row_dimensions[i].height = 60 # Col width parameters_ws.column_dimensions['A'].width = 1.5 parameters_ws.column_dimensions['B'].width = 25.0 for i in range(3, 12 + parameters_names_len * 3): parameters_ws.column_dimensions[format_cell.get_column_letter(i)].width = 15.0 # Img img = Image("excelexporters/myems.png") parameters_ws.add_image(img, 'A1') # Title parameters_ws['B3'].alignment = b_r_alignment parameters_ws['B3'] = 'Name:' parameters_ws['C3'].border = b_border parameters_ws['C3'].alignment = b_c_alignment parameters_ws['C3'] = name parameters_ws['D3'].alignment = b_r_alignment parameters_ws['D3'] = 'Period:' parameters_ws['E3'].border = b_border parameters_ws['E3'].alignment = b_c_alignment parameters_ws['E3'] = period_type parameters_ws['B4'].alignment = b_r_alignment parameters_ws['B4'] = 'Reporting Start Datetime:' parameters_ws['C4'].border = b_border parameters_ws['C4'].alignment = b_c_alignment parameters_ws['C4'] = reporting_start_datetime_local parameters_ws['D4'].alignment = b_r_alignment parameters_ws['D4'] = 'Reporting End Datetime:' parameters_ws['E4'].border = b_border parameters_ws['E4'].alignment = b_c_alignment parameters_ws['E4'] = reporting_end_datetime_local parameters_ws_current_row_number = 6 parameters_ws['B' + str(parameters_ws_current_row_number)].font = title_font parameters_ws['B' + str(parameters_ws_current_row_number)] = name + ' ' + 'Parameters' parameters_ws_current_row_number += 1 parameters_table_start_row_number = parameters_ws_current_row_number parameters_ws.row_dimensions[parameters_ws_current_row_number].height = 80 parameters_ws_current_row_number += 1 table_current_col_number = 2 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border parameters_ws[col + str(parameters_ws_current_row_number - 1)].font = name_font parameters_ws[col + str(parameters_ws_current_row_number - 1)].alignment = c_c_alignment parameters_ws[col + str(parameters_ws_current_row_number - 1)] = parameters_data['names'][i] table_current_row_number = parameters_ws_current_row_number for j, value in enumerate(list(parameters_data['timestamps'][i])): col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = value col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = round(parameters_data['values'][i][j], 2) table_current_row_number += 1 table_current_col_number = table_current_col_number + 3 ################################################################################################################ # parameters chart and parameters table ################################################################################################################ ws['B' + str(current_sheet_parameters_row_number)].font = title_font ws['B' + str(current_sheet_parameters_row_number)] = name + ' ' + 'Parameters' current_sheet_parameters_row_number += 1 chart_start_row_number = current_sheet_parameters_row_number col_index = 0 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue line = LineChart() data_col = 3 + col_index * 3 labels_col = 2 + col_index * 3 col_index += 1 line.title = 'Parameters - ' + \ parameters_ws.cell(row=parameters_table_start_row_number, column=data_col).value labels = Reference(parameters_ws, min_col=labels_col, min_row=parameters_table_start_row_number + 1, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line_data = Reference(parameters_ws, min_col=data_col, min_row=parameters_table_start_row_number, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = False line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number) chart_start_row_number += 6 ws.add_chart(line, chart_cell) current_sheet_parameters_row_number = chart_start_row_number current_sheet_parameters_row_number += 1 filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
from openpyxl import load_workbook from openpyxl.chart import BarChart, PieChart, Series, Reference wb = load_workbook('crime_report.xlsx') ws = wb.active chart = BarChart() data = Reference(ws, min_row=10, min_col=1, max_col=13, max_row=13) labels = Reference(ws, min_row=8, min_col=2, max_row=8, max_col=13) chart.add_data(data, from_rows=True, titles_from_data=True) chart.set_categories(labels) chart.title = 'Counterfeit Crimes by District' chart.height = 4.56 chart.width = 20.3 ws.add_chart(chart, 'B14') chart2 = PieChart() data = Reference(ws, min_row=8, min_col=15, max_col=16, max_row=8) labels = Reference(ws, min_row=7, min_col=15, max_row=7, max_col=16) chart2.add_data(data, from_rows=True) chart2.set_categories(labels) chart2.title = '% Counterfeit Crimes' chart2.height = 4.56 chart2.width = 8.45 ws.add_chart(chart2, 'N14') wb.save('lines.xlsx')
def create_platform_demographics_from_csv(self, csv_file_location): with open(csv_file_location) as f: csv_reader = csv.reader(f) ws = self.worksheets[ExcelBuilder.PlatformDemographics] if not isinstance(ws, openpyxl.worksheet.Worksheet): print("not a worksheet: " + str(ws)) return number_of_rows = 0 ws['A1'] = str(ExcelBuilder.PlatformDemographics) ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=8) font = Font(bold=True, color=colors.RED) grey = "D9D9D9" fill = PatternFill(fill_type='solid', start_color=grey, end_color=grey) alignment = Alignment(horizontal='center', vertical='center') self.set_cell_formatting(ws['A1'], font, fill, None, alignment, None) for row_index, row in enumerate(csv_reader): number_of_rows += 1 for column_index, csv_cell in enumerate(row): column_letter = get_column_letter(column_index + 1) row_lookup_index = str(row_index + 2) this_cell = ws[str(column_letter + row_lookup_index)] if not isinstance(this_cell, openpyxl.cell.Cell): print("what the hell is going on. not a cell?!: " + str(this_cell)) continue this_cell.value = csv_cell font = None fill = None border = None alignment = None number_format = None if column_index == 1 and str(csv_cell).isdigit(): number_format = openpyxl.styles.numbers.FORMAT_NUMBER this_cell.value = int(csv_cell) self.set_cell_formatting(this_cell, font, fill, border, alignment, number_format) # Create and add pie chart pie = PieChart() labels = Reference(ws, min_col=1, min_row=2, max_col=1, max_row=number_of_rows + 1) data = Reference(ws, min_col=2, min_row=2, max_col=2, max_row=number_of_rows + 1) pie.add_data(data) pie.set_categories(labels) pie.title = None pie.style = 2 pie.height = 13 pie.width = 21.55 ws.add_chart(pie, anchor='A2') # Add the last note ws['A28'] = "NOTE: Which platforms are being utilized the most by the attendees? For more info visit " \ "socioevents.com or reach us at [email protected]!" ws.merge_cells(start_row=28, start_column=1, end_row=30, end_column=8) font = Font(bold=True, ) alignment = Alignment(horizontal='left', wrap_text=True, vertical='top') self.set_cell_formatting(ws['A28'], font, fill, None, alignment, None) os.remove(csv_file_location)
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active ws.title = "CombinedEquipmentSaving" # Row height ws.row_dimensions[1].height = 102 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 42 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('L')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Arial', size=15, bold=True) title_font = Font(name='Arial', size=15, bold=True) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000') ) b_border = Border( bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") ws.add_image(img, 'A1') # Title ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'] = name ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'] = period_type ws['B4'].alignment = b_r_alignment ws['B4'] = 'Reporting Start Datetime:' ws['C4'].border = b_border ws['C4'].alignment = b_c_alignment ws['C4'] = reporting_start_datetime_local ws['D4'].alignment = b_r_alignment ws['D4'] = 'Reporting End Datetime:' ws['E4'].border = b_border ws['E4'].alignment = b_c_alignment ws['E4'] = reporting_end_datetime_local if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename #################################################################################################################### current_row_number = 6 reporting_period_data = report['reporting_period'] has_names_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_names_data_flag = False if has_names_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + 'Reporting Period Savings' current_row_number += 1 category = reporting_period_data['names'] ca_len = len(category) ws.row_dimensions[current_row_number].height = 75 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].border = f_border col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = reporting_period_data['names'][i] + ' ' + \ '(Baseline - Actual)(' + reporting_period_data['units'][i] + ")" col = chr(ord(col) + 1) ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = 'Ton of Standard Coal(Baseline - Actual)(TCE)' col = chr(ord(col) + 1) ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = 'Ton of Carbon Dioxide Emissions(Baseline - Actual)(TCO2E)' col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = 'Savings' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['subtotals_saving'][i], 2) col = chr(ord(col) + 1) ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['total_in_kgce_saving'] / 1000, 2) col = chr(ord(col) + 1) ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['total_in_kgco2e_saving'] / 1000, 2) col = chr(ord(col) + 1) current_row_number += 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = 'Increment Rate' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = str( round(reporting_period_data['increment_rates_saving'][i] * 100, 2)) + '%' \ if reporting_period_data['increment_rates_saving'][i] is not None else '-' col = chr(ord(col) + 1) ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = str( round(reporting_period_data['increment_rate_in_kgce_saving'] * 100, 2)) + '%' \ if reporting_period_data['increment_rate_in_kgce_saving'] is not None else '-' col = chr(ord(col) + 1) ws[col + str(current_row_number)].font = name_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = str( round(reporting_period_data['increment_rate_in_kgco2e_saving'] * 100, 2)) + '%' \ if reporting_period_data['increment_rate_in_kgco2e_saving'] is not None else '-' col = chr(ord(col) + 1) current_row_number += 2 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + 'Ton of Standard Coal(TCE) by Energy Category' current_row_number += 1 table_start_row_number = current_row_number chart_start_row_number = current_row_number ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = 'Savings' ws['D' + str(current_row_number)].fill = table_fill ws['D' + str(current_row_number)].font = name_font ws['D' + str(current_row_number)].alignment = c_c_alignment ws['D' + str(current_row_number)].border = f_border ws['D' + str(current_row_number)] = 'Ton of Standard Coal(TCE) by Energy Category' current_row_number += 1 subtotals_in_kgce_saving_sum = sum_list(reporting_period_data['subtotals_in_kgce_saving']) for i in range(0, ca_len): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = reporting_period_data['names'][i] ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round(reporting_period_data['subtotals_in_kgce_saving'][i] / 1000, 3) ws['D' + str(current_row_number)].font = name_font ws['D' + str(current_row_number)].alignment = c_c_alignment ws['D' + str(current_row_number)].border = f_border ws['D' + str(current_row_number)] = str(round(reporting_period_data['subtotals_in_kgce_saving'][i] / subtotals_in_kgce_saving_sum * 100, 2)) + '%'\ if abs(subtotals_in_kgce_saving_sum) > 0 else '-' current_row_number += 1 table_end_row_number = current_row_number - 1 if ca_len < 4: current_row_number = current_row_number - ca_len + 4 current_row_number += 1 pie = PieChart() pie.title = name + ' ' + 'Ton of Standard Coal(TCE) by Energy Category' labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 7.25 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True ws.add_chart(pie, 'E' + str(chart_start_row_number)) ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + 'Ton of Carbon Dioxide Emissions(TCO2E) by Energy Category' current_row_number += 1 table_start_row_number = current_row_number chart_start_row_number = current_row_number ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = 'Savings' ws['D' + str(current_row_number)].fill = table_fill ws['D' + str(current_row_number)].font = name_font ws['D' + str(current_row_number)].alignment = c_c_alignment ws['D' + str(current_row_number)].border = f_border ws['D' + str(current_row_number)] = 'Ton of Carbon Dioxide Emissions(TCO2E) by Energy Category' current_row_number += 1 subtotals_in_kgco2e_saving_sum = sum_list(reporting_period_data['subtotals_in_kgco2e_saving']) for i in range(0, ca_len): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = reporting_period_data['names'][i] ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round(reporting_period_data['subtotals_in_kgco2e_saving'][i] / 1000, 3) ws['D' + str(current_row_number)].font = name_font ws['D' + str(current_row_number)].alignment = c_c_alignment ws['D' + str(current_row_number)].border = f_border ws['D' + str(current_row_number)] = str(round(reporting_period_data['subtotals_in_kgco2e_saving'][i] / subtotals_in_kgco2e_saving_sum * 100, 2)) + '%'\ if abs(subtotals_in_kgco2e_saving_sum) > 0 else '-' current_row_number += 1 table_end_row_number = current_row_number - 1 if ca_len < 4: current_row_number = current_row_number - ca_len + 4 current_row_number += 1 pie = PieChart() pie.title = name + ' ' + 'Ton of Carbon Dioxide Emissions(TCO2E) by Energy Category' labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 7.25 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True ws.add_chart(pie, 'E' + str(chart_start_row_number)) #################################################################################################################### has_values_saving_data = True has_timestamps_data = True if 'values_saving' not in reporting_period_data.keys() or \ reporting_period_data['values_saving'] is None or \ len(reporting_period_data['values_saving']) == 0: has_values_saving_data = False if 'timestamps' not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0 or \ len(reporting_period_data['timestamps'][0]) == 0: has_timestamps_data = False if has_values_saving_data and has_timestamps_data: ca_len = len(reporting_period_data['names']) time = reporting_period_data['timestamps'][0] real_timestamps_len = timestamps_data_not_equal_0(report['parameters']['timestamps']) ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + 'Detailed Data' current_row_number += 1 chart_start_row_number = current_row_number current_row_number += ca_len * 6 + real_timestamps_len * 7 + 1 table_start_row_number = current_row_number ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = 'Datetime' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" col = chr(ord(col) + 1) current_row_number += 1 for i in range(0, len(time)): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = time[i] col = 'C' for j in range(0, ca_len): ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['values_saving'][j][i], 2) \ if reporting_period_data['values_saving'][j][i] is not None else 0.00 col = chr(ord(col) + 1) current_row_number += 1 table_end_row_number = current_row_number - 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = 'Subtotal' col = 'C' for i in range(0, ca_len): ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)].border = f_border ws[col + str(current_row_number)] = round(reporting_period_data['subtotals_saving'][i], 2) col = chr(ord(col) + 1) current_row_number += 2 format_time_width_number = 1.0 min_len_number = 1.0 min_width_number = 11.0 # format_time_width_number * min_len_number + 4 and min_width_number > 11.0 if period_type == 'hourly': format_time_width_number = 4.0 min_len_number = 2 min_width_number = 12.0 elif period_type == 'daily': format_time_width_number = 2.5 min_len_number = 4 min_width_number = 14.0 elif period_type == 'monthly': format_time_width_number = 2.1 min_len_number = 4 min_width_number = 12.4 elif period_type == 'yearly': format_time_width_number = 1.5 min_len_number = 5 min_width_number = 11.5 for i in range(0, ca_len): line = LineChart() line.title = 'Reporting Period Savings - ' + \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) line_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.height = 8.25 line.width = format_time_width_number * len(time) if len(time) > min_len_number else min_width_number if line.width > 24: line.width = 24 line.x_axis.crosses = 'min' line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = True line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number) chart_start_row_number += 6 ws.add_chart(line, chart_cell) #################################################################################################################### has_associated_equipment_flag = True if "associated_equipment" not in report.keys() or \ "energy_category_names" not in report['associated_equipment'].keys() or \ len(report['associated_equipment']["energy_category_names"]) == 0 \ or 'associated_equipment_names_array' not in report['associated_equipment'].keys() \ or report['associated_equipment']['associated_equipment_names_array'] is None \ or len(report['associated_equipment']['associated_equipment_names_array']) == 0 \ or len(report['associated_equipment']['associated_equipment_names_array'][0]) == 0: has_associated_equipment_flag = False if has_associated_equipment_flag: associated_equipment = report['associated_equipment'] ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' ' + 'Associated Equipment Data' current_row_number += 1 table_start_row_number = current_row_number ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = name_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)] = 'Associated Equipment' ca_len = len(associated_equipment['energy_category_names']) for i in range(0, ca_len): row = chr(ord('C') + i) ws[row + str(current_row_number)].fill = table_fill ws[row + str(current_row_number)].font = name_font ws[row + str(current_row_number)].alignment = c_c_alignment ws[row + str(current_row_number)].border = f_border ws[row + str(current_row_number)] = \ reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")" associated_equipment_len = len(associated_equipment['associated_equipment_names_array'][0]) for i in range(0, associated_equipment_len): current_row_number += 1 row = str(current_row_number) ws['B' + row].font = title_font ws['B' + row].alignment = c_c_alignment ws['B' + row] = associated_equipment['associated_equipment_names_array'][0][i] ws['B' + row].border = f_border for j in range(0, ca_len): col = chr(ord('C') + j) ws[col + row].font = title_font ws[col + row].alignment = c_c_alignment ws[col + row] = round(associated_equipment['subtotals_saving_array'][j][i], 2) ws[col + row].border = f_border #################################################################################################################### current_sheet_parameters_row_number = chart_start_row_number + 1 has_parameters_names_and_timestamps_and_values_data = True if 'parameters' not in report.keys() or \ report['parameters'] is None or \ 'names' not in report['parameters'].keys() or \ report['parameters']['names'] is None or \ len(report['parameters']['names']) == 0 or \ 'timestamps' not in report['parameters'].keys() or \ report['parameters']['timestamps'] is None or \ len(report['parameters']['timestamps']) == 0 or \ 'values' not in report['parameters'].keys() or \ report['parameters']['values'] is None or \ len(report['parameters']['values']) == 0 or \ timestamps_data_all_equal_0(report['parameters']['timestamps']): has_parameters_names_and_timestamps_and_values_data = False if has_parameters_names_and_timestamps_and_values_data: ################################################################################################################ # new worksheet ################################################################################################################ parameters_data = report['parameters'] parameters_names_len = len(parameters_data['names']) file_name = (re.sub(r'[^A-Z]', '', ws.title)) + 'aving_' parameters_ws = wb.create_sheet(file_name + 'Parameters') parameters_timestamps_data_max_len = \ get_parameters_timestamps_lists_max_len(list(parameters_data['timestamps'])) # Row height parameters_ws.row_dimensions[1].height = 102 for i in range(2, 7 + 1): parameters_ws.row_dimensions[i].height = 42 for i in range(8, parameters_timestamps_data_max_len + 10): parameters_ws.row_dimensions[i].height = 60 # Col width parameters_ws.column_dimensions['A'].width = 1.5 parameters_ws.column_dimensions['B'].width = 25.0 for i in range(3, 12+parameters_names_len*3): parameters_ws.column_dimensions[format_cell.get_column_letter(i)].width = 15.0 # Img img = Image("excelexporters/myems.png") parameters_ws.add_image(img, 'A1') # Title parameters_ws['B3'].alignment = b_r_alignment parameters_ws['B3'] = 'Name:' parameters_ws['C3'].border = b_border parameters_ws['C3'].alignment = b_c_alignment parameters_ws['C3'] = name parameters_ws['D3'].alignment = b_r_alignment parameters_ws['D3'] = 'Period:' parameters_ws['E3'].border = b_border parameters_ws['E3'].alignment = b_c_alignment parameters_ws['E3'] = period_type parameters_ws['B4'].alignment = b_r_alignment parameters_ws['B4'] = 'Reporting Start Datetime:' parameters_ws['C4'].border = b_border parameters_ws['C4'].alignment = b_c_alignment parameters_ws['C4'] = reporting_start_datetime_local parameters_ws['D4'].alignment = b_r_alignment parameters_ws['D4'] = 'Reporting End Datetime:' parameters_ws['E4'].border = b_border parameters_ws['E4'].alignment = b_c_alignment parameters_ws['E4'] = reporting_end_datetime_local parameters_ws_current_row_number = 6 parameters_ws['B' + str(parameters_ws_current_row_number)].font = title_font parameters_ws['B' + str(parameters_ws_current_row_number)] = name + ' ' + 'Parameters' parameters_ws_current_row_number += 1 parameters_table_start_row_number = parameters_ws_current_row_number parameters_ws.row_dimensions[parameters_ws_current_row_number].height = 80 parameters_ws_current_row_number += 1 table_current_col_number = 2 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(parameters_ws_current_row_number-1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number-1)].border = f_border col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(parameters_ws_current_row_number-1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number-1)].border = f_border parameters_ws[col + str(parameters_ws_current_row_number-1)].font = name_font parameters_ws[col + str(parameters_ws_current_row_number-1)].alignment = c_c_alignment parameters_ws[col + str(parameters_ws_current_row_number-1)] = parameters_data['names'][i] table_current_row_number = parameters_ws_current_row_number for j, value in enumerate(list(parameters_data['timestamps'][i])): col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = value col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = round(parameters_data['values'][i][j], 2) table_current_row_number += 1 table_current_col_number = table_current_col_number + 3 ################################################################################################################ # parameters chart and parameters table ################################################################################################################ ws['B' + str(current_sheet_parameters_row_number)].font = title_font ws['B' + str(current_sheet_parameters_row_number)] = name + ' ' + 'Parameters' current_sheet_parameters_row_number += 1 chart_start_row_number = current_sheet_parameters_row_number col_index = 0 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue line = LineChart() data_col = 3+col_index*3 labels_col = 2+col_index*3 col_index += 1 line.title = 'Parameters - ' + \ parameters_ws.cell(row=parameters_table_start_row_number, column=data_col).value labels = Reference(parameters_ws, min_col=labels_col, min_row=parameters_table_start_row_number + 1, max_row=(len(parameters_data['timestamps'][i])+parameters_table_start_row_number)) line_data = Reference(parameters_ws, min_col=data_col, min_row=parameters_table_start_row_number, max_row=(len(parameters_data['timestamps'][i])+parameters_table_start_row_number)) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = False line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number) chart_start_row_number += 6 ws.add_chart(line, chart_cell) current_sheet_parameters_row_number = chart_start_row_number current_sheet_parameters_row_number += 1 #################################################################################################################### filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename
def generate_excel(report, name, reporting_start_datetime_local, reporting_end_datetime_local, period_type): wb = Workbook() ws = wb.active # Row height ws.row_dimensions[1].height = 102 for i in range(2, 2000 + 1): ws.row_dimensions[i].height = 42 # for i in range(2, 37 + 1): # ws.row_dimensions[i].height = 30 # # for i in range(38, 90 + 1): # ws.row_dimensions[i].height = 30 # Col width ws.column_dimensions['A'].width = 1.5 ws.column_dimensions['B'].width = 25.0 for i in range(ord('C'), ord('L')): ws.column_dimensions[chr(i)].width = 15.0 # Font name_font = Font(name='Constantia', size=15, bold=True) title_font = Font(name='宋体', size=15, bold=True) data_font = Font(name='Franklin Gothic Book', size=11) table_fill = PatternFill(fill_type='solid', fgColor='1F497D') f_border = Border(left=Side(border_style='medium', color='00000000'), right=Side(border_style='medium', color='00000000'), bottom=Side(border_style='medium', color='00000000'), top=Side(border_style='medium', color='00000000')) b_border = Border(bottom=Side(border_style='medium', color='00000000'), ) b_c_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_c_alignment = Alignment(vertical='center', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) b_r_alignment = Alignment(vertical='bottom', horizontal='right', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) c_r_alignment = Alignment(vertical='bottom', horizontal='center', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0) # Img img = Image("excelexporters/myems.png") img.width = img.width * 0.85 img.height = img.height * 0.85 # img = Image("myems.png") ws.add_image(img, 'B1') # Title ws.row_dimensions[3].height = 60 ws['B3'].font = name_font ws['B3'].alignment = b_r_alignment ws['B3'] = 'Name:' ws['C3'].border = b_border ws['C3'].alignment = b_c_alignment ws['C3'].font = name_font ws['C3'] = name ws['D3'].font = name_font ws['D3'].alignment = b_r_alignment ws['D3'] = 'Period:' ws['E3'].border = b_border ws['E3'].alignment = b_c_alignment ws['E3'].font = name_font ws['E3'] = period_type ws['F3'].font = name_font ws['F3'].alignment = b_r_alignment ws['F3'] = 'Date:' ws['G3'].border = b_border ws['G3'].alignment = b_c_alignment ws['G3'].font = name_font ws['G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local ws.merge_cells("G3:H3") if "reporting_period" not in report.keys() or \ "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0: filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename ################################################# reporting_period_data = report['reporting_period'] has_energy_data_flag = True if "names" not in reporting_period_data.keys() or \ reporting_period_data['names'] is None or \ len(reporting_period_data['names']) == 0: has_energy_data_flag = False if has_energy_data_flag: ws['B6'].font = title_font ws['B6'] = name + ' 报告期消耗' category = reporting_period_data['names'] ca_len = len(category) ws.row_dimensions[7].height = 60 ws['B7'].fill = table_fill ws['B8'].font = title_font ws['B8'].alignment = c_c_alignment ws['B8'] = '能耗' ws['B8'].border = f_border ws['B9'].font = title_font ws['B9'].alignment = c_c_alignment ws['B9'] = '单位面积能耗' ws['B9'].border = f_border ws['B10'].font = title_font ws['B10'].alignment = c_c_alignment ws['B10'] = '环比' ws['B10'].border = f_border col = 'B' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + '7'].fill = table_fill ws[col + '7'].font = name_font ws[col + '7'].alignment = c_c_alignment ws[col + '7'] = reporting_period_data['names'][ i] + " (" + reporting_period_data['units'][i] + ")" ws[col + '7'].border = f_border ws[col + '8'].font = name_font ws[col + '8'].alignment = c_c_alignment ws[col + '8'] = round(reporting_period_data['subtotals'][i], 2) ws[col + '8'].border = f_border ws[col + '9'].font = name_font ws[col + '9'].alignment = c_c_alignment ws[col + '9'] = round( reporting_period_data['subtotals_per_unit_area'][i], 2) ws[col + '9'].border = f_border ws[col + '10'].font = name_font ws[col + '10'].alignment = c_c_alignment ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \ if reporting_period_data['increment_rates'][i] is not None else "-" ws[col + '10'].border = f_border # TCE TCO2E end_col = col # TCE tce_col = chr(ord(end_col) + 1) ws[tce_col + '7'].fill = table_fill ws[tce_col + '7'].font = name_font ws[tce_col + '7'].alignment = c_c_alignment ws[tce_col + '7'] = "吨标准煤 (TCE)" ws[tce_col + '7'].border = f_border ws[tce_col + '8'].font = name_font ws[tce_col + '8'].alignment = c_c_alignment ws[tce_col + '8'] = round( reporting_period_data['total_in_kgce'] / 1000, 2) ws[tce_col + '8'].border = f_border ws[tce_col + '9'].font = name_font ws[tce_col + '9'].alignment = c_c_alignment ws[tce_col + '9'] = round( reporting_period_data['total_in_kgce_per_unit_area'] / 1000, 2) ws[tce_col + '9'].border = f_border ws[tce_col + '10'].font = name_font ws[tce_col + '10'].alignment = c_c_alignment ws[tce_col + '10'] = str(round(reporting_period_data['increment_rate_in_kgce'] * 100, 2)) + "%" \ if reporting_period_data['increment_rate_in_kgce'] is not None else "-" ws[tce_col + '10'].border = f_border # TCO2E tco2e_col = chr(ord(end_col) + 2) ws[tco2e_col + '7'].fill = table_fill ws[tco2e_col + '7'].font = name_font ws[tco2e_col + '7'].alignment = c_c_alignment ws[tco2e_col + '7'] = "吨二氧化碳排放 (TCO2E)" ws[tco2e_col + '7'].border = f_border ws[tco2e_col + '8'].font = name_font ws[tco2e_col + '8'].alignment = c_c_alignment ws[tco2e_col + '8'] = round( reporting_period_data['total_in_kgco2e'] / 1000, 2) ws[tco2e_col + '8'].border = f_border ws[tco2e_col + '9'].font = name_font ws[tco2e_col + '9'].alignment = c_c_alignment ws[tco2e_col + '9'] = round( reporting_period_data['total_in_kgco2e_per_unit_area'] / 1000, 2) ws[tco2e_col + '9'].border = f_border ws[tco2e_col + '10'].font = name_font ws[tco2e_col + '10'].alignment = c_c_alignment ws[tco2e_col + '10'] = str(round(reporting_period_data['increment_rate_in_kgco2e'] * 100, 2)) + "%" \ if reporting_period_data['increment_rate_in_kgco2e'] is not None else "-" ws[tco2e_col + '10'].border = f_border else: for i in range(6, 10 + 1): ws.row_dimensions[i].height = 0.1 ################################################# has_ele_peak_flag = True if "toppeaks" not in reporting_period_data.keys() or \ reporting_period_data['toppeaks'] is None or \ len(reporting_period_data['toppeaks']) == 0: has_ele_peak_flag = False if has_ele_peak_flag: ws['B12'].font = title_font ws['B12'] = name + ' 分时电耗' ws['B13'].fill = table_fill ws['B13'].font = name_font ws['B13'].alignment = c_c_alignment ws['B13'].border = f_border ws['C13'].fill = table_fill ws['C13'].font = name_font ws['C13'].alignment = c_c_alignment ws['C13'].border = f_border ws['C13'] = '分时电耗' ws['B14'].font = title_font ws['B14'].alignment = c_c_alignment ws['B14'] = '尖' ws['B14'].border = f_border ws['C14'].font = title_font ws['C14'].alignment = c_c_alignment ws['C14'].border = f_border ws['C14'] = round(reporting_period_data['toppeaks'][0], 2) ws['B15'].font = title_font ws['B15'].alignment = c_c_alignment ws['B15'] = '峰' ws['B15'].border = f_border ws['C15'].font = title_font ws['C15'].alignment = c_c_alignment ws['C15'].border = f_border ws['C15'] = round(reporting_period_data['onpeaks'][0], 2) ws['B16'].font = title_font ws['B16'].alignment = c_c_alignment ws['B16'] = '平' ws['B16'].border = f_border ws['C16'].font = title_font ws['C16'].alignment = c_c_alignment ws['C16'].border = f_border ws['C16'] = round(reporting_period_data['midpeaks'][0], 2) ws['B17'].font = title_font ws['B17'].alignment = c_c_alignment ws['B17'] = '谷' ws['B17'].border = f_border ws['C17'].font = title_font ws['C17'].alignment = c_c_alignment ws['C17'].border = f_border ws['C17'] = round(reporting_period_data['offpeaks'][0], 2) pie = PieChart() pie.title = name + ' 分时电耗' labels = Reference(ws, min_col=2, min_row=14, max_row=17) pie_data = Reference(ws, min_col=3, min_row=13, max_row=17) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 6.6 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True ws.add_chart(pie, "D13") else: for i in range(12, 18 + 1): ws.row_dimensions[i].height = 0.1 ################################################ current_row_number = 19 has_kgce_data_flag = True if "subtotals_in_kgce" not in reporting_period_data.keys() or \ reporting_period_data['subtotals_in_kgce'] is None or \ len(reporting_period_data['subtotals_in_kgce']) == 0: has_kgce_data_flag = False if has_kgce_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 吨标准煤 (TCE) 占比' current_row_number += 1 table_start_row_number = current_row_number ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = name_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = '吨标准煤 (TCE) 占比' current_row_number += 1 ca_len = len(reporting_period_data['names']) for i in range(0, ca_len): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = reporting_period_data['names'][i] ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].font = title_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round( reporting_period_data['subtotals_in_kgce'][i] / 1000, 3) current_row_number += 1 table_end_row_number = current_row_number - 1 pie = PieChart() pie.title = name + ' ' + ws.cell(column=3, row=table_start_row_number).value labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 7.25 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True table_cell = 'D' + str(table_start_row_number) ws.add_chart(pie, table_cell) if ca_len < 4: current_row_number = current_row_number - ca_len + 4 else: for i in range(21, 29 + 1): current_row_number = 30 ws.row_dimensions[i].height = 0.1 ##################################################### current_row_number += 1 has_kgco2e_data_flag = True if "subtotals_in_kgco2e" not in reporting_period_data.keys() or \ reporting_period_data['subtotals_in_kgco2e'] is None or \ len(reporting_period_data['subtotals_in_kgco2e']) == 0: has_kgco2e_data_flag = False if has_kgco2e_data_flag: ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 吨二氧化碳排放 (TCO2E) 占比' current_row_number += 1 table_start_row_number = current_row_number ws.row_dimensions[current_row_number].height = 75 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = name_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].fill = table_fill ws['C' + str(current_row_number)].font = name_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = '吨二氧化碳排放 (TCO2E) 占比' current_row_number += 1 ca_len = len(reporting_period_data['names']) for i in range(0, ca_len): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = reporting_period_data['names'][i] ws['B' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)].font = title_font ws['C' + str(current_row_number)].alignment = c_c_alignment ws['C' + str(current_row_number)].border = f_border ws['C' + str(current_row_number)] = round( reporting_period_data['subtotals_in_kgco2e'][i] / 1000, 3) current_row_number += 1 table_end_row_number = current_row_number - 1 pie = PieChart() pie.title = name + ' ' + ws.cell(column=3, row=table_start_row_number).value labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number) pie.add_data(pie_data, titles_from_data=True) pie.set_categories(labels) pie.height = 7.75 pie.width = 9 s1 = pie.series[0] s1.dLbls = DataLabelList() s1.dLbls.showCatName = False s1.dLbls.showVal = True s1.dLbls.showPercent = True table_cell = 'D' + str(table_start_row_number) ws.add_chart(pie, table_cell) if ca_len < 4: current_row_number = current_row_number - ca_len + 4 else: for i in range(30, 39 + 1): current_row_number = 40 ws.row_dimensions[i].height = 0.1 ############################################### current_row_number += 1 has_detail_data_flag = True table_start_draw_flag = current_row_number + 1 if "timestamps" not in reporting_period_data.keys() or \ reporting_period_data['timestamps'] is None or \ len(reporting_period_data['timestamps']) == 0: has_detail_data_flag = False if has_detail_data_flag: reporting_period_data = report['reporting_period'] times = reporting_period_data['timestamps'] ca_len = len(report['reporting_period']['names']) real_timestamps_len = timestamps_data_not_equal_0( report['parameters']['timestamps']) ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)] = name + ' 详细数据' table_start_row_number = (current_row_number + 1) + ca_len * 6 + real_timestamps_len * 7 current_row_number = table_start_row_number time = times[0] has_data = False if len(time) > 0: has_data = True if has_data: ws.row_dimensions[current_row_number].height = 60 ws['B' + str(current_row_number)].fill = table_fill ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].border = f_border ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = '日期时间' for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(current_row_number)].fill = table_fill ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)] = reporting_period_data['names'][i] + \ " (" + reporting_period_data['units'][i] + ")" ws[col + str(current_row_number)].border = f_border current_row_number += 1 for i in range(0, len(time)): ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = time[i] ws['B' + str(current_row_number)].border = f_border for j in range(0, ca_len): col = chr(ord('C') + j) ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)] = round( reporting_period_data['values'][j][i], 2) ws[col + str(current_row_number)].border = f_border current_row_number += 1 table_end_row_number = current_row_number - 1 ws['B' + str(current_row_number)].font = title_font ws['B' + str(current_row_number)].alignment = c_c_alignment ws['B' + str(current_row_number)] = '小计' ws['B' + str(current_row_number)].border = f_border for i in range(0, ca_len): col = chr(ord('C') + i) ws[col + str(current_row_number)].font = title_font ws[col + str(current_row_number)].alignment = c_c_alignment ws[col + str(current_row_number)] = round( reporting_period_data['subtotals'][i], 2) ws[col + str(current_row_number)].border = f_border # line line = LineChart() line.title = '报告期消耗 - ' + ws.cell( column=3 + i, row=table_start_row_number).value labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number) line_data = Reference(ws, min_col=3 + i, min_row=table_start_row_number, max_row=table_end_row_number) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = True line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(table_start_draw_flag + 6 * i) ws.add_chart(line, chart_cell) current_row_number += 1 else: for i in range(40, 69 + 1): current_row_number = 70 ws.row_dimensions[i].height = 0.1 ########################################## current_sheet_parameters_row_number = table_start_draw_flag + ca_len * 6 + 1 has_parameters_names_and_timestamps_and_values_data = True if 'parameters' not in report.keys() or \ report['parameters'] is None or \ 'names' not in report['parameters'].keys() or \ report['parameters']['names'] is None or \ len(report['parameters']['names']) == 0 or \ 'timestamps' not in report['parameters'].keys() or \ report['parameters']['timestamps'] is None or \ len(report['parameters']['timestamps']) == 0 or \ 'values' not in report['parameters'].keys() or \ report['parameters']['values'] is None or \ len(report['parameters']['values']) == 0 or \ timestamps_data_all_equal_0(report['parameters']['timestamps']): has_parameters_names_and_timestamps_and_values_data = False if has_parameters_names_and_timestamps_and_values_data: ############################### # new worksheet ############################### parameters_data = report['parameters'] parameters_names_len = len(parameters_data['names']) parameters_ws = wb.create_sheet('相关参数') parameters_timestamps_data_max_len = \ get_parameters_timestamps_lists_max_len(list(parameters_data['timestamps'])) # Row height parameters_ws.row_dimensions[1].height = 102 for i in range(2, 7 + 1): parameters_ws.row_dimensions[i].height = 42 for i in range(8, parameters_timestamps_data_max_len + 10): parameters_ws.row_dimensions[i].height = 60 # Col width parameters_ws.column_dimensions['A'].width = 1.5 parameters_ws.column_dimensions['B'].width = 25.0 for i in range(3, 12 + parameters_names_len * 3): parameters_ws.column_dimensions[format_cell.get_column_letter( i)].width = 15.0 # Img img = Image("excelexporters/myems.png") img.width = img.width * 0.85 img.height = img.height * 0.85 # img = Image("myems.png") parameters_ws.add_image(img, 'B1') # Title parameters_ws.row_dimensions[3].height = 60 parameters_ws['B3'].font = name_font parameters_ws['B3'].alignment = b_r_alignment parameters_ws['B3'] = 'Name:' parameters_ws['C3'].border = b_border parameters_ws['C3'].alignment = b_c_alignment parameters_ws['C3'].font = name_font parameters_ws['C3'] = name parameters_ws['D3'].font = name_font parameters_ws['D3'].alignment = b_r_alignment parameters_ws['D3'] = 'Period:' parameters_ws['E3'].border = b_border parameters_ws['E3'].alignment = b_c_alignment parameters_ws['E3'].font = name_font parameters_ws['E3'] = period_type parameters_ws['F3'].font = name_font parameters_ws['F3'].alignment = b_r_alignment parameters_ws['F3'] = 'Date:' parameters_ws['G3'].border = b_border parameters_ws['G3'].alignment = b_c_alignment parameters_ws['G3'].font = name_font parameters_ws[ 'G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local parameters_ws.merge_cells("G3:H3") parameters_ws_current_row_number = 6 parameters_ws['B' + str(parameters_ws_current_row_number)].font = title_font parameters_ws['B' + str(parameters_ws_current_row_number)] = name + ' 相关参数' parameters_ws_current_row_number += 1 parameters_table_start_row_number = parameters_ws_current_row_number parameters_ws.row_dimensions[ parameters_ws_current_row_number].height = 80 parameters_ws_current_row_number += 1 table_current_col_number = 2 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border parameters_ws[col + str(parameters_ws_current_row_number - 1)].font = name_font parameters_ws[col + str(parameters_ws_current_row_number - 1)].alignment = c_c_alignment parameters_ws[col + str(parameters_ws_current_row_number - 1)] = parameters_data['names'][i] table_current_row_number = parameters_ws_current_row_number for j, value in enumerate(list(parameters_data['timestamps'][i])): col = format_cell.get_column_letter(table_current_col_number) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = value col = format_cell.get_column_letter(table_current_col_number + 1) parameters_ws[col + str(table_current_row_number)].border = f_border parameters_ws[col + str(table_current_row_number)].font = title_font parameters_ws[ col + str(table_current_row_number)].alignment = c_c_alignment parameters_ws[col + str(table_current_row_number)] = round( parameters_data['values'][i][j], 2) table_current_row_number += 1 table_current_col_number = table_current_col_number + 3 ######################################################## # parameters chart and parameters table ######################################################## ws['B' + str(current_sheet_parameters_row_number)].font = title_font ws['B' + str(current_sheet_parameters_row_number)] = name + ' 相关参数' current_sheet_parameters_row_number += 1 chart_start_row_number = current_sheet_parameters_row_number col_index = 0 for i in range(0, parameters_names_len): if len(parameters_data['timestamps'][i]) == 0: continue line = LineChart() data_col = 3 + col_index * 3 labels_col = 2 + col_index * 3 col_index += 1 line.title = '相关参数 - ' + \ parameters_ws.cell(row=parameters_table_start_row_number, column=data_col).value labels = Reference(parameters_ws, min_col=labels_col, min_row=parameters_table_start_row_number + 1, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line_data = Reference( parameters_ws, min_col=data_col, min_row=parameters_table_start_row_number, max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number)) line.add_data(line_data, titles_from_data=True) line.set_categories(labels) line_data = line.series[0] line_data.marker.symbol = "circle" line_data.smooth = True line.x_axis.crosses = 'min' line.height = 8.25 line.width = 24 line.dLbls = DataLabelList() line.dLbls.dLblPos = 't' line.dLbls.showVal = False line.dLbls.showPercent = False chart_col = 'B' chart_cell = chart_col + str(chart_start_row_number) chart_start_row_number += 6 ws.add_chart(line, chart_cell) current_sheet_parameters_row_number = chart_start_row_number current_sheet_parameters_row_number += 1 ########################################## filename = str(uuid.uuid4()) + '.xlsx' wb.save(filename) return filename