Example #1
0
# Plot Bar chart
chart_values = xl.chart.Reference(sheet,
                                  min_row=2,
                                  max_row=4,
                                  min_col=4,
                                  max_col=4)

chart_type = xl.chart.BarChart()
chart_type.add_data(chart_values)
sheet.add_chart(chart_type, "e1")

# Plot pie char with details
chart_title = "Pie Chart"
chart_catagories = xl.chart.Reference(sheet, min_col=1, min_row=2, max_row=4)
chart_data = Reference(sheet, min_col=4, min_row=1, max_row=4)

chart = PieChart()
chart.title = chart_title
chart.set_categories(chart_catagories)
chart.add_data(chart_data, titles_from_data=True)

sheet.add_chart(chart, "e1")

# Insert row/cols from index to length
sheet.insert_rows(2, 2)
sheet.insert_cols(2, 2)

# Delete rows/coloumn from index to length
sheet.delete_rows(5, 3)
sheet.delete_cols(5, 2)
import openpyxl
from openpyxl.chart import RadarChart, Reference

wb = openpyxl.load_workbook(r"..\data\radar_chart.xlsx")
sh = wb.active

data = Reference(sh, min_col=2, max_col=4, min_row=1, max_row=sh.max_row)
labels = Reference(sh, min_col=1, min_row=2, max_row=sh.max_row)

chart = RadarChart()
#デフォルトはstandard
#filledは塗りつぶし
#chart.type = "filled"
chart.title = "部門別売上"
chart.add_data(data, titles_from_data=True)
chart.set_categories(labels)

sh.add_chart(chart, "F2")
wb.save(r"..\data\radar_chart.xlsx")
Example #3
0
wb = Workbook()
ws = wb.active

rows = [
    ['Number', 'Batch 1', 'Batch 2'],
    ['A', 40, 60],
    ['B', 40, 75],
    ['C', 50, 60],
    ['D', 30, 50],
    ['E', 25, 65],
    ['F', 50, 70],
]

for row in rows:
    ws.append(row)

chart = AreaChart3D()
chart.title = "Area Chart"
chart.style = 13
chart.x_axis.title = 'Test'
chart.y_axis.title = 'Percentage'

# yData needs to start on row=1 to include titles
xData = Reference(ws, min_col=1, min_row=2, max_row=7)
yData = Reference(ws, min_col=2, max_col=3, min_row=1, max_row=7)
chart.add_data(yData, titles_from_data=True)
chart.set_categories(xData)
ws.add_chart(chart, "B10")

wb.save('data/charts3D.xlsx')
def test_monitor(file_in, file_out):
    print("Generate {} ==> {}".format(file_in, file_out))
    wb_tpl = Workbook()
    ws = wb_tpl.active
    # ws = wb_tpl.worksheets[0]
    ws.title = "Monitor"
    """ [ [2018/06/17 23:47:11,17.0,16.71], [2018/06/17 23:47:13,1.5,17.01], [2018/06/17 23:47:15,2.9,17.04], ... ] """
    data_list = CSVUtils.readCSVRowsList(file_in)
    _max_row = len(data_list)
    _max_col = 3
    for row_index, rows in enumerate(data_list):
        for col_index, value in enumerate(rows):
            if (row_index == 0):
                ws.cell(row=row_index + 1, column=col_index + 1).value = value
            else:
                if (col_index == 0):
                    ws.cell(row=row_index + 1,
                            column=col_index + 1).value = datetime.strptime(
                                value, DATE_TIME_FORMAT)
                    ws.cell(row=row_index + 1,
                            column=col_index + 1).number_format = 'HH:mm:ss'
                else:
                    ws.cell(row=row_index + 1,
                            column=col_index + 1).value = float(value)

    ws['E1'] = "CPU(AVG):"
    ws['E2'] = "Memory(AVG):"
    ws['F1'] = "=AVERAGE(B:B)"
    ws['F2'] = "=AVERAGE(C:C)"
    chart1 = LineChart()
    chart1.title = "CPU/Memory Monitor"
    chart1.style = 2  # default style when new a line chart
    chart1.height = 15  # default is 7.5
    chart1.width = 30  # default is 15
    chart1.legend.position = "b"
    chart1.y_axis.scaling.min = 0
    chart1.y_axis.scaling.max = 100
    # chart1.y_axis.title = 'Pecent'
    # chart1.x_axis.title = 'Time'

    # set y-axis
    data = Reference(ws,
                     min_col=2,
                     min_row=1,
                     max_col=_max_col,
                     max_row=_max_row)
    chart1.add_data(data, titles_from_data=True)

    # set time as category(x-axis)
    cats = Reference(ws, min_col=1, min_row=2, max_row=_max_row)
    chart1.set_categories(cats)

    # Style the lines
    # s1 = c1.series[0]
    # s1.marker.symbol = "triangle"
    # s1.marker.graphicalProperties.solidFill = "FF0000" # Marker filling
    # s1.marker.graphicalProperties.line.solidFill = "FF0000" # Marker outline

    # s1.graphicalProperties.line.noFill = True

    s2 = chart1.series[0]
    s2.smooth = True  # Make the line smooth
    # s2.graphicalProperties.line.solidFill = "00AAAA"
    # s2.graphicalProperties.line.dashStyle = "sysDot"
    # s2.graphicalProperties.line.width = 100050 # width in EMUs

    s2 = chart1.series[1]
    s2.smooth = True  # Make the line smooth
    # chart1.x_axis.tickLblPos = "low"
    # chart1.x_axis.tickLblSkip = 3 # whatever you like
    ws.add_chart(chart1, "F10")

    # dest_filename = file_out
    wb_tpl.save(filename=file_out)
    print("%s ====> %s" % (file_in, file_out))
Example #5
0
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
Example #6
0
import openpyxl
from openpyxl.chart import AreaChart3D, Reference

wb = openpyxl.Workbook()

sheet = wb.active

for i in range(10):
    sheet.append([i])

values = Reference(sheet, min_col=1, min_row=1, max_col=1, max_row=10)

chart = AreaChart3D()

chart.add_data(values)

chart.title = "Area Chart3D"
chart.x_axis.title = " X_Axis"
chart.y_axis.title = " Y_Axis"

sheet.add_chart(chart, 'E2')

wb.save("Areachart3d.xlsx")
Example #7
0
for row in ws.iter_rows(min_col=2,
                        min_row=2,
                        max_col=ws.max_column,
                        max_row=ws.max_row):
    for cell in row:
        res = int(''.join(list(filter(str.isdigit, cell.value))))
        print(res)

#%%
# BubbleChart class의 객체 생성
chart = LineChart()

# 플로팅 데이터 생성
data = Reference(ws,
                 min_col=1,
                 min_row=1,
                 max_col=ws.max_column,
                 max_row=ws.max_row)

# 차트 객체에 시리즈 데이터 추가
chart.add_data(data, titles_from_data=True)

# 차트 타이틀
chart.title = wss[0]

# # x축 타이틀
# chart.x_axis.title = ws['A1']

# # y축 타이틀
# chart.y_axis.title = ws['B1']
Example #8
0
# Pie chart
ws = wb.active
ws.title = 'pieChart'

data = [
    ['Pie', 'Sold'],
    ['Apple', 50],
    ['Cherry', 30],
    ['Pumpkin', 10],
    ['Chocolate', 40],
]
for row in data:
    ws.append(row)

pie = PieChart()
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
data = Reference(ws, min_col=2, min_row=2, max_row=5)
pie.add_data(data)
pie.set_categories(labels)
pie.title = 'Pie sold by category'
ws.add_chart(pie, 'A15')

# Bar chart
ws = wb.create_sheet('barChart')

rows = [
    ('Number', 'Batch 1', 'Batch 2'),
    (2, 10, 30),
    (3, 40, 60),
    (4, 50, 70),
    (5, 20, 10),
Example #9
0
book = Workbook()
sheet = book.active

rows = [
    ("USA", 46),
    ("China", 38),
    ("UK", 29),
    ("Russia", 22),
    ("South Korea", 13),
    ("Germany", 11)
]

for row in rows:
    sheet.append(row)

data = Reference(sheet, min_col=2, min_row=1, max_col=2, max_row=6)
categs = Reference(sheet, min_col=1, min_row=1, max_row=6)

chart = BarChart()
chart.add_data(data=data)
chart.set_categories(categs)

chart.legend = None
chart.y_axis.majorGridlines = None
chart.varyColors = True
chart.title = "Olympic Gold medals in London"

sheet.add_chart(chart, "A8")

book.save("bar_chart.xlsx")
Example #10
0
import openpyxl
from openpyxl.chart import BarChart, Reference, Series

workbook = openpyxl.load_workbook("bmi.xlsx")
sheet = workbook["Sheet1"]

chart = BarChart()

# first column is used as label, starting from row 2
labels = Reference(sheet, min_col=1, min_row=2, max_row=3)

# first row is used for header, that is why min_row is 1
data = Reference(sheet, min_col=3, min_row=1, max_row=3)

chart.add_data(data, titles_from_data=True)
chart.set_categories(labels)
chart.title = "Bar Chart"
chart.x_axis.title = "Name"
chart.y_axis.title = "Height"
chart.series[0].SeriesLabel = "height"

sheet.add_chart(chart, 'E1')
workbook.save('bmi_chart.xlsx')
Example #11
0
from openpyxl import load_workbook
wb = load_workbook("sample.xlsx")
ws = wb.active

from openpyxl.chart import BarChart, Reference, LineChart
# bar_value = Reference(ws, min_row=2, max_row=11, min_col=2, max_col=3)
# bar_chart = BarChart() #차트 종류 설정
# bar_chart.add_data(bar_value)# 차트 데이터 추가

# ws.add_chart(bar_chart, "E1") #차트 넣을 위치 정ㅇ의

line_value = Reference(ws, min_row=1, max_row=11, min_col=2, max_col=3)
line_chart = LineChart()
line_chart.add_data(line_value, titles_from_data=True)
line_chart.title = "성적표"
line_chart.style = 10
line_chart.y_axis.title = "점수"
line_chart.x_axis.title = "번호"
ws.add_chart(line_chart, "E1")

wb.save("sample_chart.xlsx")
Example #12
0
#!/usr/bin/env 
# -python3*- coding: utf-8 -*-
"""
Created on Mon Aug 24 19:01:54 2020

@author: emmanuelidehen
"""
import pandas as pd
import numpy as np
import openpyxl
from openpyxl import load_workbook
from openpyxl import worksheet
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.chart import BarChart, PieChart, Reference



wb = load_workbook('Numerical_Analysis_Emmanuel_idehen_Report.xlsx')

ws = wb.active 
chart = BarChart()
data = Reference(ws, min_row=8, min_col = 1, max_col=13, max_row=13 )

chart.add_data(data, titles_from_data=True)
ws.add_chart(chart, 'B14')
wb.save('line.xlsx')
Example #13
0
    def max_mean(self):
        keyword = "Odau"
        file_list = os.listdir(self.process_folder)
        for file in file_list:
            if "rms.txt" in file_list:
                print("已绘图")
                break
            else:
                if keyword in file:
                    print(file)
                    data = pd.read_excel(self.process_folder + file, sheet_name="RMS")
                    if self.upper_limb:
                        col = {1: "RMS_1_三角肌前束",
                               2: "RMS_2_三角肌后束",
                               3: "RMS_3_肱二头肌",
                               4: "RMS_4_肱三头肌",
                               5: "RMS_5_桡侧腕屈肌",
                               6: "RMS_6_尺侧腕伸肌"}

                    else:
                        col = {1: "RMS_1_股直肌",
                               2: "RMS_2_股二头肌",
                               3: "RMS_3_半腱肌",
                               4: "RMS_4_股内侧肌",
                               5: "RMS_5_胫骨前肌",
                               6: "RMS_6_外侧腓肠肌"
                               }
                    # ["time", "RMS_1_股直肌", "RMS_2_股二头肌", "RMS_3_半腱肌", "RMS_4_股内侧肌", "RMS_5_胫骨前肌", "RMS_6_外侧腓肠肌"]

                    # 取最大的前40%的值,求平均
                    frames = len(data)
                    max_frames = int(0.2 * frames)
                    rms_max = ["RMS_max", 0, 0, 0, 0, 0, 0]

                    for i in range(1, 7):
                        temp = data.iloc[data[col[i]].argsort()[-max_frames:]]
                        # print("debug1",temp)
                        rms_max[i] = mean(temp[col[i]])

                        # print("debug2", rms_max)
                    print(rms_max)

                    wb = openpyxl.load_workbook(self.process_folder + file)
                    # print("open and plot:", self.process_folder + file)
                    ws = wb["RMS"]
                    ws.append(rms_max)
                    wb.save(self.process_folder + file)

                    wb = openpyxl.load_workbook(self.process_folder + file)
                    ws = wb["RMS"]
                    chart = BarChart()
                    cats = Reference(ws, min_col=2, max_col=7, min_row=1)
                    chart.set_categories(cats)
                    chart.width = 20
                    chart.height = 10
                    chart.x_axis.title = "time/s"
                    chart.y_axis.title = "RMS/mV"
                    chart.y_axis.scaling.max = 0.5
                    rms_max_data = Reference(ws, min_col=2, max_col=7, min_row=frames+1)
                    chart.add_data(rms_max_data)
                    ws.add_chart(chart, "I20")
                    wb.save(self.process_folder + file)
Example #14
0
    elif i > 80 and i <=90:
        i = 'Q' + str((i-81)*7+1)
        sheet2.add_image(img3, i)    
    
    else:
        i = 'S' +str((i-91)*7+1)
        sheet2.add_image(img3, i)

book.save("./data/meltop100.xlsx")

# Trythis 3-1번
book = openpyxl.load_workbook("./data/meltop100.xlsx")
sheet3=book.create_sheet()
sheet3.title = "차트출력"

datax = Reference(sheet1, min_col=4, 
		min_row=2, max_col=4, max_row=11)
categs = Reference(sheet1, min_col=2,
				 min_row=2,max_row= 11)

chart1 = BarChart()
chart1.add_data(datax)
chart1.set_categories(categs)

chart1.legend = None  # 범례
chart1.varyColors = True
chart1.title = "상위 10위 좋아요수"
sheet3.add_chart(chart1, "A8")

# Trythis 3-2번
chart2 = ScatterChart()
chart2.style = 13
Example #15
0
    ["Time", "jitter", "rtt", "loss"],
    ["09:25:35.584", 10, 50, 0],
    ["09:26:35.584", 20, 55, 10],
    ["09:27:35.584", 30, 60, 20],
]

for row in rows:
    ws.append(row)

c1 = LineChart()
c1.title = "Line Chart"
c1.style = 13
c1.y_axis.title = 'Size'
c1.x_axis.title = 'Test Number'

data = Reference(ws, min_col=2, min_row=1, max_col=4, max_row=7)
c1.add_data(data, titles_from_data=True)

# Style the lines
s1 = c1.series[0]
s1.marker.symbol = "triangle"
s1.marker.graphicalProperties.solidFill = "FF0000"  # Marker filling
s1.marker.graphicalProperties.line.solidFill = "FF0000"  # Marker outline

s1.graphicalProperties.line.noFill = True

s2 = c1.series[1]
s2.graphicalProperties.line.solidFill = "00AAAA"
s2.graphicalProperties.line.dashStyle = "sysDot"
s2.graphicalProperties.line.width = 100050  # width in EMUs
Example #16
0
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'].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 \
            "difference_values" not in report['reporting_period'].keys() or \
            len(report['reporting_period']['difference_values']) == 0:
        filename = str(uuid.uuid4()) + '.xlsx'
        wb.save(filename)

        return filename
    #################################################

    has_difference_values_data_flag = True
    if 'difference_values' not in report['reporting_period'].keys() or len(
            report['reporting_period']['difference_values']) == 0:
        has_difference_values_data_flag = False

    current_row_number = 6

    if has_difference_values_data_flag:
        reporting_period_data = report['reporting_period']
        category = report['meter']['energy_category_name']

        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)].border = f_border
        if not isinstance(category, list):
            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)] = report['meter']['energy_category_name'] + " (" + report['meter'][
                'unit_of_measure'] + ")"

            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)] = '总表消耗'

            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['master_meter_consumption_in_category'], 2)

            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)] = '分表消耗'

            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['submeters_consumption_in_category'], 2)

            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)] = '差值'

            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['difference_in_category'], 2)

            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)] = '差值百分比'

            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)] = str(
                round(reporting_period_data['percentage_difference'] * 100, 2)) + '%'

            current_row_number += 2

            time = reporting_period_data['timestamps']
            parameters_names_len = len(report['parameters']['names'])
            parameters_data = report['parameters']
            parameters_parameters_datas_len = 0
            for i in range(0, parameters_names_len):
                if len(parameters_data['timestamps'][i]) == 0:
                    continue
                parameters_parameters_datas_len += 1
            has_time_data_flag = False
            if time is not None and len(time) > 0:
                has_time_data_flag = True

            if has_time_data_flag:

                ws['B' + str(current_row_number)].font = title_font
                ws['B' + str(current_row_number)] = name + ' 详细数据'

                current_row_number += 1
                chart_start_number = current_row_number
                current_row_number = current_row_number + 1 + len(category) * 6 + parameters_parameters_datas_len * 6
                table_start_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)].border = f_border
                ws['B' + str(current_row_number)].alignment = c_c_alignment
                ws['B' + str(current_row_number)] = '日期时间'

                ws['C' + str(current_row_number)].fill = table_fill
                ws['C' + str(current_row_number)].font = title_font
                ws['C' + str(current_row_number)].border = f_border
                ws['C' + str(current_row_number)].alignment = c_c_alignment
                ws['C' + str(current_row_number)] = report['meter']['energy_category_name'] + " (" + report['meter'][
                    'unit_of_measure'] + ")"

                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)].border = f_border
                    ws['B' + str(current_row_number)].alignment = c_c_alignment
                    ws['B' + str(current_row_number)] = time[i]

                    ws['C' + str(current_row_number)].font = title_font
                    ws['C' + str(current_row_number)].border = f_border
                    ws['C' + str(current_row_number)].alignment = c_c_alignment
                    ws['C' + str(current_row_number)] = round(reporting_period_data['difference_values'][i], 2)

                    current_row_number += 1

                table_end_number = current_row_number - 1

                line = LineChart()
                line.title = '报告期差值 - ' + report['meter']['energy_category_name'] + " (" + report['meter'][
                    'unit_of_measure'] + ")"
                labels = Reference(ws, min_col=2, min_row=table_start_number + 1, max_row=table_end_number)
                line_data = Reference(ws, min_col=3, min_row=table_start_number, max_row=table_end_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  # 数量显示
                ws.add_chart(line, "B" + str(chart_start_number))

                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)] = '总计'

                ws['C' + str(current_row_number)].font = title_font
                ws['C' + str(current_row_number)].border = f_border
                ws['C' + str(current_row_number)].alignment = c_c_alignment
                ws['C' + str(current_row_number)] = round(reporting_period_data['master_meter_consumption_in_category']
                                                          , 2)

        else:
            pass

    ##########################################
    has_parameters_names_and_timestamps_and_values_data = True
    # 12 is the starting line number of the last line chart in the report period
    category = report['meter']['energy_category_name']
    ca_len = len(category)
    time_len = len(report['reporting_period']['timestamps'])
    current_sheet_parameters_row_number = 14 + 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 = '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 = decimal_to_column(column_to_decimal(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 = decimal_to_column(column_to_decimal(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 = decimal_to_column(column_to_decimal(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)

    filename = str(uuid.uuid4()) + '.xlsx'
    wb.save(filename)

    return filename
Example #17
0
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=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)

    # 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~ca_len table_data
    #################################################
    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

        filename = str(uuid.uuid4()) + '.xlsx'
        wb.save(filename)

        return filename

    if has_energy_data_flag:
        ws['B6'].font = title_font
        ws['B6'] = name + ' 统计分析'

        category = reporting_period_data['names']

        # table_title
        ws['B7'].fill = table_fill
        ws['B7'].font = title_font
        ws['B7'].alignment = c_c_alignment
        ws['B7'] = '报告期'
        ws['B7'].border = f_border

        ws['C7'].font = title_font
        ws['C7'].alignment = c_c_alignment
        ws['C7'] = '算术平均数'
        ws['C7'].border = f_border

        ws['D7'].font = title_font
        ws['D7'].alignment = c_c_alignment
        ws['D7'] = '中位数'
        ws['D7'].border = f_border

        ws['E7'].font = title_font
        ws['E7'].alignment = c_c_alignment
        ws['E7'] = '最小值'
        ws['E7'].border = f_border

        ws['F7'].font = title_font
        ws['F7'].alignment = c_c_alignment
        ws['F7'] = '最大值'
        ws['F7'].border = f_border

        ws['G7'].font = title_font
        ws['G7'].alignment = c_c_alignment
        ws['G7'] = '样本标准差'
        ws['G7'].border = f_border

        ws['H7'].font = title_font
        ws['H7'].alignment = c_c_alignment
        ws['H7'] = '样本方差'
        ws['H7'].border = f_border

        # table_data

        for i, value in enumerate(category):
            row = i*2 + 8
            ws['B' + str(row)].font = name_font
            ws['B' + str(row)].alignment = c_c_alignment
            ws['B' + str(row)] = reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + " )"
            ws['B' + str(row)].border = f_border

            ws['B' + str(row + 1)].font = name_font
            ws['B' + str(row + 1)].alignment = c_c_alignment
            ws['B' + str(row + 1)] = "环比"
            ws['B' + str(row + 1)].border = f_border

            ws['C' + str(row)].font = name_font
            ws['C' + str(row)].alignment = c_c_alignment
            ws['C' + str(row)] = round(reporting_period_data['means'][i], 2) \
                if reporting_period_data['means'][i] is not None else ''
            ws['C' + str(row)].border = f_border
            ws['C' + str(row)].number_format = '0.00'

            ws['C' + str(row + 1)].font = name_font
            ws['C' + str(row + 1)].alignment = c_c_alignment
            ws['C' + str(row + 1)] = str(round(reporting_period_data['means_increment_rate'][i] * 100, 2)) + "%" \
                if reporting_period_data['means_increment_rate'][i] is not None else '0.00%'
            ws['C' + str(row + 1)].border = f_border

            ws['D' + str(row)].font = name_font
            ws['D' + str(row)].alignment = c_c_alignment
            ws['D' + str(row)] = round(reporting_period_data['medians'][i], 2) \
                if reporting_period_data['medians'][i] is not None else ''
            ws['D' + str(row)].border = f_border
            ws['D' + str(row)].number_format = '0.00'

            ws['D' + str(row + 1)].font = name_font
            ws['D' + str(row + 1)].alignment = c_c_alignment
            ws['D' + str(row + 1)] = str(round(reporting_period_data['medians_increment_rate'][i] * 100, 2)) + "%" \
                if reporting_period_data['medians_increment_rate'][i] is not None else '0.00%'
            ws['D' + str(row + 1)].border = f_border

            ws['E' + str(row)].font = name_font
            ws['E' + str(row)].alignment = c_c_alignment
            ws['E' + str(row)] = round(reporting_period_data['minimums'][i], 2) \
                if reporting_period_data['minimums'][i] is not None else ''
            ws['E' + str(row)].border = f_border
            ws['E' + str(row)].number_format = '0.00'

            ws['E' + str(row + 1)].font = name_font
            ws['E' + str(row + 1)].alignment = c_c_alignment
            ws['E' + str(row + 1)] = str(round(reporting_period_data['minimums_increment_rate'][i] * 100, 2)) + "%" \
                if reporting_period_data['minimums_increment_rate'][i] is not None else '0.00%'
            ws['E' + str(row + 1)].border = f_border

            ws['F' + str(row)].font = name_font
            ws['F' + str(row)].alignment = c_c_alignment
            ws['F' + str(row)] = round(reporting_period_data['maximums'][i], 2) \
                if reporting_period_data['maximums'][i] is not None else ''
            ws['F' + str(row)].border = f_border
            ws['F' + str(row)].number_format = '0.00'

            ws['F' + str(row + 1)].font = name_font
            ws['F' + str(row + 1)].alignment = c_c_alignment
            ws['F' + str(row + 1)] = str(round(reporting_period_data['maximums_increment_rate'][i] * 100, 2)) + "%" \
                if reporting_period_data['maximums_increment_rate'][i] is not None else '0.00%'
            ws['F' + str(row + 1)].border = f_border

            ws['G' + str(row)].font = name_font
            ws['G' + str(row)].alignment = c_c_alignment
            ws['G' + str(row)] = round(reporting_period_data['stdevs'][i], 2) \
                if reporting_period_data['stdevs'][i] is not None else ''
            ws['G' + str(row)].border = f_border
            ws['G' + str(row)].number_format = '0.00'

            ws['G' + str(row + 1)].font = name_font
            ws['G' + str(row + 1)].alignment = c_c_alignment
            ws['G' + str(row + 1)] = str(round(reporting_period_data['stdevs_increment_rate'][i] * 100, 2)) + "%" \
                if reporting_period_data['stdevs_increment_rate'][i] is not None else '0.00%'
            ws['G' + str(row + 1)].border = f_border

            ws['H' + str(row)].font = name_font
            ws['H' + str(row)].alignment = c_c_alignment
            ws['H' + str(row)] = round(reporting_period_data['variances'][i], 2) \
                if reporting_period_data['variances'][i] is not None else ''
            ws['H' + str(row)].border = f_border
            ws['H' + str(row)].number_format = '0.00'

            ws['H' + str(row + 1)].font = name_font
            ws['H' + str(row + 1)].alignment = c_c_alignment
            ws['H' + str(row + 1)] = str(round(reporting_period_data['variances_increment_rate'][i] * 100, 2)) + "%" \
                if reporting_period_data['variances_increment_rate'][i] is not None else '0.00%'
            ws['H' + str(row + 1)].border = f_border
    #################################################
    # Second: 报告期消耗
    # 9 + ca_len * 2: title
    # 10 + ca_len * 2: table title
    # per_unit_area_start_row_number + 2 ~ per_unit_area_start_row_number + 2 + ca_len :  table_data
    #################################################

    if has_energy_data_flag:
        names = reporting_period_data['names']
        ca_len = len(names)

        per_unit_area_start_row_number = 9 + ca_len * 2

        ws['B' + str(per_unit_area_start_row_number)].font = title_font
        ws['B' + str(per_unit_area_start_row_number)] = name + ' 单位面积值' + str(report['tenant']['area']) + 'M²'

        category = reporting_period_data['names']

        # table_title
        ws['B' + str(per_unit_area_start_row_number + 1)].fill = table_fill
        ws['B' + str(per_unit_area_start_row_number + 1)].font = title_font
        ws['B' + str(per_unit_area_start_row_number + 1)].alignment = c_c_alignment
        ws['B' + str(per_unit_area_start_row_number + 1)] = '报告期'
        ws['B' + str(per_unit_area_start_row_number + 1)].border = f_border

        ws['C' + str(per_unit_area_start_row_number + 1)].font = title_font
        ws['C' + str(per_unit_area_start_row_number + 1)].alignment = c_c_alignment
        ws['C' + str(per_unit_area_start_row_number + 1)] = '算术平均数'
        ws['C' + str(per_unit_area_start_row_number + 1)].border = f_border

        ws['D' + str(per_unit_area_start_row_number + 1)].font = title_font
        ws['D' + str(per_unit_area_start_row_number + 1)].alignment = c_c_alignment
        ws['D' + str(per_unit_area_start_row_number + 1)] = '中位数'
        ws['D' + str(per_unit_area_start_row_number + 1)].border = f_border

        ws['E' + str(per_unit_area_start_row_number + 1)].font = title_font
        ws['E' + str(per_unit_area_start_row_number + 1)].alignment = c_c_alignment
        ws['E' + str(per_unit_area_start_row_number + 1)] = '最小值'
        ws['E' + str(per_unit_area_start_row_number + 1)].border = f_border

        ws['F' + str(per_unit_area_start_row_number + 1)].font = title_font
        ws['F' + str(per_unit_area_start_row_number + 1)].alignment = c_c_alignment
        ws['F' + str(per_unit_area_start_row_number + 1)] = '最大值'
        ws['F' + str(per_unit_area_start_row_number + 1)].border = f_border

        ws['G' + str(per_unit_area_start_row_number + 1)].font = title_font
        ws['G' + str(per_unit_area_start_row_number + 1)].alignment = c_c_alignment
        ws['G' + str(per_unit_area_start_row_number + 1)] = '样本标准差'
        ws['G' + str(per_unit_area_start_row_number + 1)].border = f_border

        ws['H' + str(per_unit_area_start_row_number + 1)].font = title_font
        ws['H' + str(per_unit_area_start_row_number + 1)].alignment = c_c_alignment
        ws['H' + str(per_unit_area_start_row_number + 1)] = '样本方差'
        ws['H' + str(per_unit_area_start_row_number + 1)].border = f_border

        # table_data

        for i, value in enumerate(category):
            row_data = per_unit_area_start_row_number + 2 + i
            ws['B' + str(row_data)].font = name_font
            ws['B' + str(row_data)].alignment = c_c_alignment
            ws['B' + str(row_data)] = reporting_period_data['names'][i] + " (" + reporting_period_data['units'][
                i] + "/M²)"
            ws['B' + str(row_data)].border = f_border

            ws['C' + str(row_data)].font = name_font
            ws['C' + str(row_data)].alignment = c_c_alignment
            if reporting_period_data['means_per_unit_area'][i] \
                    or reporting_period_data['means_per_unit_area'][i] == 0:
                ws['C' + str(row_data)] = round(reporting_period_data['means_per_unit_area'][i], 2)
            ws['C' + str(row_data)].border = f_border
            ws['C' + str(row_data)].number_format = '0.00'

            ws['D' + str(row_data)].font = name_font
            ws['D' + str(row_data)].alignment = c_c_alignment
            if reporting_period_data['medians_per_unit_area'][i] \
                    or reporting_period_data['medians_per_unit_area'][i] == 0:
                ws['D' + str(row_data)] = round(reporting_period_data['medians_per_unit_area'][i], 2)
            ws['D' + str(row_data)].border = f_border
            ws['D' + str(row_data)].number_format = '0.00'

            ws['E' + str(row_data)].font = name_font
            ws['E' + str(row_data)].alignment = c_c_alignment
            if reporting_period_data['minimums_per_unit_area'][i] \
                    or reporting_period_data['minimums_per_unit_area'][i] == 0:
                ws['E' + str(row_data)] = round(reporting_period_data['minimums_per_unit_area'][i], 2)
            ws['E' + str(row_data)].border = f_border
            ws['E' + str(row_data)].number_format = '0.00'

            ws['F' + str(row_data)].font = name_font
            ws['F' + str(row_data)].alignment = c_c_alignment
            if reporting_period_data['maximums_per_unit_area'][i] \
                    or reporting_period_data['maximums_per_unit_area'][i] == 0:
                ws['F' + str(row_data)] = round(reporting_period_data['maximums_per_unit_area'][i], 2)
            ws['F' + str(row_data)].border = f_border
            ws['F' + str(row_data)].number_format = '0.00'

            ws['G' + str(row_data)].font = name_font
            ws['G' + str(row_data)].alignment = c_c_alignment
            if (reporting_period_data['stdevs_per_unit_area'][i]) \
                    or reporting_period_data['stdevs_per_unit_area'][i] == 0:
                ws['G' + str(row_data)] = round(reporting_period_data['stdevs_per_unit_area'][i], 2)
            ws['G' + str(row_data)].border = f_border
            ws['G' + str(row_data)].number_format = '0.00'

            ws['H' + str(row_data)].font = name_font
            ws['H' + str(row_data)].alignment = c_c_alignment
            if reporting_period_data['variances_per_unit_area'][i] \
                    or reporting_period_data['variances_per_unit_area'][i] == 0:
                ws['H' + str(row_data)] = round(reporting_period_data['variances_per_unit_area'][i], 2)
            ws['H' + str(row_data)].border = f_border
            ws['H' + str(row_data)].number_format = '0.00'

    ########################################################
    # Third: 详细数据
    # detailed_start_row_number~ detailed_start_row_number+time_len: line
    # detailed_start_row_number + 1: table title
    # i + analysis_end_row_number + 2 + 6 * ca_len~: table_data
    ########################################################
    has_timestamps_flag = True
    if "timestamps" not in reporting_period_data.keys() or \
            reporting_period_data['timestamps'] is None or \
            len(reporting_period_data['timestamps']) == 0:
        has_timestamps_flag = False

    if has_timestamps_flag:
        timestamps = reporting_period_data['timestamps'][0]
        values = reporting_period_data['values']
        names = reporting_period_data['names']
        ca_len = len(names)
        time_len = len(timestamps)
        real_timestamps_len = timestamps_data_not_equal_0(report['parameters']['timestamps'])
        # title
        line_charts_row_number = 6 * ca_len + real_timestamps_len * 7
        analysis_end_row_number = 12 + 3 * ca_len
        detailed_start_row_number = analysis_end_row_number + line_charts_row_number + 1

        ws['B' + str(detailed_start_row_number)].font = title_font
        ws['B' + str(detailed_start_row_number)] = name + ' 详细数据'
        # table_title
        ws['B' + str(detailed_start_row_number + 1)].fill = table_fill
        ws['B' + str(detailed_start_row_number + 1)].font = name_font
        ws['B' + str(detailed_start_row_number + 1)].alignment = c_c_alignment
        ws['B' + str(detailed_start_row_number + 1)] = "时间"
        ws['B' + str(detailed_start_row_number + 1)].border = f_border

        for i in range(0, ca_len):
            col = chr(ord('C') + i)

            ws[col + str(detailed_start_row_number + 1)].font = name_font
            ws[col + str(detailed_start_row_number + 1)].alignment = c_c_alignment
            ws[col + str(detailed_start_row_number + 1)] = names[i] + " - (" + reporting_period_data['units'][i] + ")"
            ws[col + str(detailed_start_row_number + 1)].border = f_border
        # table_date
        for i in range(0, time_len):
            rows = i + detailed_start_row_number + 2

            ws['B' + str(rows)].font = name_font
            ws['B' + str(rows)].alignment = c_c_alignment
            ws['B' + str(rows)] = timestamps[i]
            ws['B' + str(rows)].border = f_border

            for index in range(0, ca_len):
                col = chr(ord('C') + index)

                ws[col + str(rows)].font = name_font
                ws[col + str(rows)].alignment = c_c_alignment
                ws[col + str(rows)] = round(values[index][i], 2)
                ws[col + str(rows)].number_format = '0.00'
                ws[col + str(rows)].border = f_border

        # 小计
        row_subtotals = detailed_start_row_number + 2 + time_len
        ws['B' + str(row_subtotals)].font = name_font
        ws['B' + str(row_subtotals)].alignment = c_c_alignment
        ws['B' + str(row_subtotals)] = "小计"
        ws['B' + str(row_subtotals)].border = f_border

        for i in range(0, ca_len):
            col = chr(ord('C') + i)

            ws[col + str(row_subtotals)].font = name_font
            ws[col + str(row_subtotals)].alignment = c_c_alignment
            ws[col + str(row_subtotals)] = round(reporting_period_data['subtotals'][i], 2)
            ws[col + str(row_subtotals)].border = f_border
            ws[col + str(row_subtotals)].number_format = '0.00'

    ########################################################
    # third: LineChart
    # LineChart requires data from the detailed data table in the Excel file
    # so print the detailed data table first and then print LineChart
    ########################################################
        for i in range(0, ca_len):

            line = LineChart()
            line.title = "报告期消耗" + " - " + names[i] + "(" + reporting_period_data['units'][i] + ")"
            line.style = 10
            line.x_axis.majorTickMark = 'in'
            line.y_axis.majorTickMark = 'in'
            line.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
            times = Reference(ws, min_col=2, min_row=detailed_start_row_number + 2,
                              max_row=detailed_start_row_number + 2 + time_len)
            line_data = Reference(ws, min_col=3 + i, min_row=detailed_start_row_number + 1,
                                  max_row=detailed_start_row_number + 1 + time_len)
            line.add_data(line_data, titles_from_data=True)
            line.set_categories(times)
            ser = line.series[0]
            ser.marker.symbol = "diamond"
            ser.marker.size = 5
            ws.add_chart(line, 'B' + str(analysis_end_row_number + 6 * i))
    ##########################################
    current_sheet_parameters_row_number = analysis_end_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 = 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
Example #18
0
def SaveXlsxFile():
    wb = Workbook()
    wsSummary = wb.active
    wsSummary.title = 'Summary'

    wsSummary.append(["Name", roast.name])
    wsSummary.append(["Start Weight", roast.preWeight])
    wsSummary.append(["End Weight", roast.postWeight])
    wsSummary.append(["Weight Loss", roast.getWeightLoss()])
    wsSummary.append(["First Crack", roast.firstCrack])
    wsSummary.append(["Second Crack", roast.secondCrack])

    wsSummary['B5'].number_format = 'mm:ss.00'
    wsSummary['B6'].number_format = 'mm:ss.00'
    wsSummary.column_dimensions['A'].width = 12
    wsSummary.column_dimensions['B'].width = 25

    wsData = wb.create_sheet(title="Data")
    wsData.append([
        'Time', 'Internal Temp', 'Target Temp', 'Thermocouple Temp',
        'Delta Temp', 'Fan Speed', 'Heat', 'PID Output', 'P', 'I', 'D',
        'Heat State Index'
    ])
    for log in roaster.log:
        wsData.append(log)

    for index in range(2, len(roaster.log) + 2):
        wsData['A' + str(index)].number_format = 'mm:ss.00'

    chart = LineChart()
    chart.title = "Temperature Profile"
    chart.style = 2
    chart.y_axis.title = 'Temperature (F)'
    chart.x_axis.title = 'Time'

    data = Reference(wsData,
                     min_col=3,
                     min_row=1,
                     max_col=4,
                     max_row=len(roaster.log) + 1)
    timings = Reference(wsData,
                        min_col=1,
                        min_row=1,
                        max_col=1,
                        max_row=len(roaster.log) + 1)
    chart.add_data(data, titles_from_data=True)
    chart.set_categories(timings)

    wsSummary.add_chart(chart, "A9")

    chart2 = LineChart()
    chart2.title = "Roaster Settings"
    chart2.style = 2
    chart2.y_axis.title = 'Setting'
    chart2.x_axis.title = 'Time'

    fanHeatData = Reference(wsData,
                            min_col=5,
                            min_row=1,
                            max_col=6,
                            max_row=len(roaster.log) + 1)
    chart2.add_data(fanHeatData, titles_from_data=True)
    chart2.set_categories(timings)

    wsSummary.add_chart(chart2, "A24")
    # Save the file
    wb.save('roasts/' + roast.startTime.strftime('%y-%m-%d ') + roast.name +
            ".xlsx")
    [date(2015, 9, 3), 50, 30, 45],
    [date(2015, 9, 4), 30, 25, 40],
    [date(2015, 9, 5), 25, 35, 30],
    [date(2015, 9, 6), 20, 40, 35],
]

for row in rows:
    ws.append(row)

c1 = LineChart()
c1.title = "Line Chart"
c1.style = 13
c1.y_axis.title = 'Size'
c1.x_axis.title = 'Test Number'

data = Reference(ws, min_col=2, min_row=1, max_col=4, max_row=7)
c1.add_data(data, titles_from_data=True)
'''
print(c1.series[0])
print(c1.series[1])
print(c1.series[2])
'''

# Style the lines
s1 = c1.series[0]
s1.marker.symbol = "triangle"
s1.marker.graphicalProperties.solidFill = "FF0000"  # Marker filling
s1.marker.graphicalProperties.line.solidFill = "FF0000"  # Marker outline

s1.graphicalProperties.line.noFill = True
Example #20
0
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, 11 + 1):
    #     ws.row_dimensions[i].height = 30
    #
    # for i in range(12, 43 + 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 \
            "values" not in report['reporting_period'].keys() or len(report['reporting_period']['values']) == 0:
        filename = str(uuid.uuid4()) + '.xlsx'
        wb.save(filename)

        return filename
    #################################################
    # First: 能耗分析
    # 6: title
    # 7: table title
    # 8~9 table_data
    #################################################
    has_energy_data_flag = True

    if "values" not in report['reporting_period'].keys() or len(report['reporting_period']['values']) == 0:
        has_energy_data_flag = False

    if has_energy_data_flag:
        ws['B6'].font = title_font
        ws['B6'] = name + '能耗分析'

        reporting_period_data = report['reporting_period']
        # print(reporting_period_data)
        category = report['meter']['energy_category_name']
        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'] = report['meter']['energy_category_name'] + " (" + report['meter']['unit_of_measure'] + ")"
            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_in_category'], 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_rate'] * 100, 2)) + "%" \
                if reporting_period_data['increment_rate'] 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'] * 100, 2)) + "%" \
            if reporting_period_data['increment_rate'] 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'] * 100, 2)) + "%" \
            if reporting_period_data['increment_rate'] 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: 能耗详情
    # 11: title
    # 12 ~ 16: chart
    # 18: table title
    # 19~43: table_data
    #################################################
    has_energy_detail_flag = True
    reporting_period_data = report['reporting_period']
    times = reporting_period_data['timestamps']

    if "values" not in report['reporting_period'].keys() or len(report['reporting_period']['values']) == 0:
        has_energy_detail_flag = False

    if has_energy_detail_flag:
        reporting_period_data = report['reporting_period']
        category = report['meter']['energy_category_name']
        ca_len = len(category)
        parameters_names_len = len(report['parameters']['names'])
        parameters_data = report['parameters']
        parameters_parameters_datas_len = 0
        for i in range(0, parameters_names_len):
            if len(parameters_data['timestamps'][i]) == 0:
                continue
            parameters_parameters_datas_len += 1
        start_detail_data_row_num = 13 + (parameters_parameters_datas_len + ca_len) * 6
        ws['B11'].font = title_font
        ws['B11'] = name + '详细数据'

        ws.row_dimensions[start_detail_data_row_num].height = 60

        ws['B' + str(start_detail_data_row_num)].fill = table_fill
        ws['B' + str(start_detail_data_row_num)].font = title_font
        ws['B' + str(start_detail_data_row_num)].border = f_border
        ws['B' + str(start_detail_data_row_num)].alignment = c_c_alignment
        ws['B' + str(start_detail_data_row_num)] = '日期时间'
        time = times
        has_data = False
        max_row = 0
        if len(time) > 0:
            has_data = True
            max_row = start_detail_data_row_num + len(time)

        if has_data:
            for i in range(0, len(time)):
                col = 'B'
                row = str(start_detail_data_row_num + 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):
                # 12 title
                col = chr(ord('C') + i)

                ws[col + str(start_detail_data_row_num)].fill = table_fill
                ws[col + str(start_detail_data_row_num)].font = title_font
                ws[col + str(start_detail_data_row_num)].alignment = c_c_alignment
                ws[col + str(start_detail_data_row_num)] = report['meter']['energy_category_name'] + \
                    " (" + report['meter']['unit_of_measure'] + ")"
                ws[col + str(start_detail_data_row_num)].border = f_border

                # 13 data
                time = times
                time_len = len(time)

                for j in range(0, time_len):
                    row = str(start_detail_data_row_num + 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'][j], 2)
                    ws[col + row].border = f_border
            # line
            # 13~: line
            line = LineChart()
            line.title = '报告期消耗 - ' + report['meter']['energy_category_name'] + \
                " (" + report['meter']['unit_of_measure'] + ")"
            labels = Reference(ws, min_col=2, min_row=start_detail_data_row_num + 1, max_row=max_row)
            bar_data = Reference(ws, min_col=3, min_row=start_detail_data_row_num, max_row=max_row)
            line.add_data(bar_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_data.smooth = True
            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.showCatName = True  # 标签显示
            line.dLbls = DataLabelList()
            line.dLbls.dLblPos = 't'
            line.dLbls.showVal = True  # 数量显示
            line.dLbls.showPercent = False  # 百分比显示
            # s1 = CharacterProperties(sz=1800)     # 图表中字体大小 *100
            ws.add_chart(line, "B12")

            col = 'B'
            row = str(start_detail_data_row_num + 1 + len(time))

            ws[col + row].font = title_font
            ws[col + row].alignment = c_c_alignment
            ws[col + row] = '总计'
            ws[col + row].border = f_border

            for i in range(0, ca_len):
                col = chr(ord(col) + 1)
                ws[col + row].font = title_font
                ws[col + row].alignment = c_c_alignment
                ws[col + row] = round(reporting_period_data['total_in_category'], 2)
                ws[col + row].border = f_border

    else:
        for i in range(11, 43 + 1):
            ws.row_dimensions[i].height = 0.0

    ##########################################
    has_parameters_names_and_timestamps_and_values_data = True
    # 12 is the starting line number of the last line chart in the report period
    category = report['meter']['energy_category_name']
    time_len = len(reporting_period_data['timestamps'])
    ca_len = len(category)
    current_sheet_parameters_row_number = 12 + 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
    [date(2015, 9, 5), 25, 35, 30],
    [date(2015, 9, 6), 20, 40, 35],
]

for row in rows:
    ws.append(row)

c1 = LineChart()
c1.title = "Line Chart"  # 图的标题
c1.style = 8  # 线条的style
c1.y_axis.title = 'Size'  # y坐标的标题
c1.x_axis.title = 'Date'  # x坐标的标题
c1.x_axis.number_format = 'd-mmm'  # 规定日期格式  这是月,年格式
c1.x_axis.majorTimeUnit = "Months"  # 规定日期间隔 注意days;Months大写

data = Reference(ws, min_col=2, min_row=1, max_col=4,
                 max_row=7)  # 图像的数据 起始行、起始列、终止行、终止列
c1.add_data(data, titles_from_data=True)

ws.add_chart(c1, "A10")

# # Style the lines
# s1 = c1.series[0]
# s1.marker.symbol = "triangle"
# s1.marker.graphicalProperties.solidFill = "FF0000" # Marker filling
# s1.marker.graphicalProperties.line.solidFill = "FF0000" # Marker outline
#
# s1.graphicalProperties.line.noFill = True
#
# s2 = c1.series[1]
# s2.graphicalProperties.line.solidFill = "00AAAA"
# s2.graphicalProperties.line.dashStyle = "sysDot"
Example #22
0
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_efficiency" not in report.keys() or \
            "names" not in report['reporting_period_efficiency'].keys() or len(
            report['reporting_period_efficiency']['names']) == 0:
        filename = str(uuid.uuid4()) + '.xlsx'
        wb.save(filename)

        return filename

    ##################################

    current_row_number = 6

    reporting_period_data = report['reporting_period_efficiency']

    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 = 80
        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['cumulations'][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_parameters_names_and_timestamps_and_values_data = True
    current_sheet_parameters_row_number = current_row_number

    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

    #####################################

    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 + 1

        if has_parameters_names_and_timestamps_and_values_data:
            current_sheet_parameters_row_number = current_row_number
            real_timestamps_len = timestamps_data_not_equal_0(report['parameters']['timestamps'])
            current_row_number += 6*real_timestamps_len + 2

        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 = 85
        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['cumulations'][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)

    #####################################################################

    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
Example #23
0
    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)
Example #24
0
def generate_excel(report, name, reporting_start_datetime_local,
                   reporting_end_datetime_local, period_type):
    wb = Workbook()
    ws = wb.active
    ws.title = "ShopFloorEnergyItem"

    # 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

    chart_start_row_number = current_row_number + 1

    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)].font = title_font
        ws['B' + str(current_row_number)] = 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
        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=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 + 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 = (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
Example #25
0
def generate_excel(report, name, reporting_start_datetime_local,
                   reporting_end_datetime_local, period_type):

    wb = Workbook()
    ws = wb.active
    ws.title = "MeterEnergy"

    # 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 \
            "values" not in report['reporting_period'].keys() or len(report['reporting_period']['values']) == 0:
        filename = str(uuid.uuid4()) + '.xlsx'
        wb.save(filename)

        return filename
    ####################################################################################################################
    # First: Consumption
    # 6: title
    # 7: table title
    # 8~9 table_data
    ####################################################################################################################
    has_energy_data_flag = True

    if "values" not in report['reporting_period'].keys() or len(
            report['reporting_period']['values']) == 0:
        has_energy_data_flag = False

    if has_energy_data_flag:
        ws['B6'].font = title_font
        ws['B6'] = name + ' ' + 'Consumption'

        reporting_period_data = report['reporting_period']

        category = report['meter']['energy_category_name']
        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'] = 'Increment Rate'
        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'] = report['meter']['energy_category_name'] + " (" + report[
                   'meter']['unit_of_measure'] + ")"
            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_in_category'],
                                  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_rate'] * 100, 2)) + "%" \
                if reporting_period_data['increment_rate'] 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'] = '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'] = str(round(reporting_period_data['increment_rate'] * 100, 2)) + "%" \
            if reporting_period_data['increment_rate'] 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'] = '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'] = str(round(reporting_period_data['increment_rate'] * 100, 2)) + "%" \
            if reporting_period_data['increment_rate'] 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: Detailed Data
    # 11: title
    # 12 ~ 16: chart
    # 18: table title
    # 19~43: table_data
    ####################################################################################################################
    has_energy_detail_flag = True
    reporting_period_data = report['reporting_period']
    times = reporting_period_data['timestamps']

    if "values" not in report['reporting_period'].keys() or len(
            report['reporting_period']['values']) == 0:
        has_energy_detail_flag = False

    if has_energy_detail_flag:
        reporting_period_data = report['reporting_period']
        category = report['meter']['energy_category_name']
        ca_len = len(category)
        parameters_names_len = len(report['parameters']['names'])
        parameters_data = report['parameters']
        parameters_parameters_datas_len = 0
        for i in range(0, parameters_names_len):
            if len(parameters_data['timestamps'][i]) == 0:
                continue
            parameters_parameters_datas_len += 1
        start_detail_data_row_num = 13 + (parameters_parameters_datas_len +
                                          ca_len) * 6
        ws['B11'].font = title_font
        ws['B11'] = name + 'Detailed Data'

        ws.row_dimensions[start_detail_data_row_num].height = 60

        ws['B' + str(start_detail_data_row_num)].fill = table_fill
        ws['B' + str(start_detail_data_row_num)].font = title_font
        ws['B' + str(start_detail_data_row_num)].border = f_border
        ws['B' + str(start_detail_data_row_num)].alignment = c_c_alignment
        ws['B' + str(start_detail_data_row_num)] = 'Datetime'
        time = times
        has_data = False
        max_row = 0
        if len(time) > 0:
            has_data = True
            max_row = start_detail_data_row_num + len(time)

        if has_data:
            for i in range(0, len(time)):
                col = 'B'
                row = str(start_detail_data_row_num + 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):
                # 12 title
                col = chr(ord('C') + i)

                ws[col + str(start_detail_data_row_num)].fill = table_fill
                ws[col + str(start_detail_data_row_num)].font = title_font
                ws[col +
                   str(start_detail_data_row_num)].alignment = c_c_alignment
                ws[col + str(start_detail_data_row_num)] = report['meter']['energy_category_name'] + \
                    " (" + report['meter']['unit_of_measure'] + ")"
                ws[col + str(start_detail_data_row_num)].border = f_border

                # 13 data
                time = times
                time_len = len(time)

                for j in range(0, time_len):
                    row = str(start_detail_data_row_num + 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'][j],
                                          2)
                    ws[col + row].border = f_border
            # line
            # 13~: line
            line = LineChart()
            line.title = 'Reporting Period Consumption - ' + report['meter']['energy_category_name'] + \
                " (" + report['meter']['unit_of_measure'] + ")"
            labels = Reference(ws,
                               min_col=2,
                               min_row=start_detail_data_row_num + 1,
                               max_row=max_row)
            bar_data = Reference(ws,
                                 min_col=3,
                                 min_row=start_detail_data_row_num,
                                 max_row=max_row)
            line.add_data(bar_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 = DataLabelList()
            line.dLbls.dLblPos = 't'
            line.dLbls.showVal = True  # 数量显示
            line.dLbls.showPercent = False  # 百分比显示
            ws.add_chart(line, "B12")

            col = 'B'
            row = str(start_detail_data_row_num + 1 + len(time))

            ws[col + row].font = title_font
            ws[col + row].alignment = c_c_alignment
            ws[col + row] = 'Total'
            ws[col + row].border = f_border

            for i in range(0, ca_len):
                col = chr(ord(col) + 1)
                ws[col + row].font = title_font
                ws[col + row].alignment = c_c_alignment
                ws[col + row] = round(
                    reporting_period_data['total_in_category'], 2)
                ws[col + row].border = f_border

    else:
        for i in range(11, 43 + 1):
            ws.row_dimensions[i].height = 0.0

    ##########################################
    has_parameters_names_and_timestamps_and_values_data = True
    # 12 is the starting line number of the last line chart in the report period
    category = report['meter']['energy_category_name']
    time_len = len(reporting_period_data['timestamps'])
    ca_len = len(category)
    current_sheet_parameters_row_number = 12 + 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 = (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
                try:
                    parameters_ws[col + str(table_current_row_number)] = round(
                        parameters_data['values'][i][j], 2)
                except Exception as e:
                    print('error 1 in excelexporters\meterenergy: ' + str(e))

                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
Example #26
0
for SecondRadius in SecondRadii:
    ws.cell(row=rad_index, column=3).value = SecondRadius
    tot_arc = ((ws['C2'].value / 360) * 2 * pi * ws['C3'].value) + (
        (ws['C2'].value / 360) * 2 * pi * SecondRadius
    )  # Need to change for final version to input the excel formula into each cell
    ws.cell(row=rad_index, column=4).value = tot_arc
    rad_index += 1

irr_data = open('Test Irradiance Data.txt', 'r')
irr_index = 4
for point in irr_data:
    ws.cell(row=irr_index, column=5).value = float(point)
    irr_index += 1

irr_data.close()

chart = ScatterChart(scatterStyle='smoothMarker')
chart.x_axis.title = 'Radius of 2nd Curve (mm)'
chart.y_axis.title = '% Transmission'

xvalues = Reference(ws, min_col=3, min_row=4, max_row=22)
yvalues = Reference(ws, min_col=5, min_row=4, max_row=22)
series = Series(yvalues, xvalues)
chart.series.append(series)

ws.add_chart(chart, 'G3')

# https://openpyxl.readthedocs.io/en/stable/charts/scatter.html refer to this for next iteration with multiple lines

wb.save('TestWorkbook2.xlsx')
Example #27
0
def generate_excel(report, name, reporting_start_datetime_local,
                   reporting_end_datetime_local, period_type):
    wb = Workbook()

    # todo
    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'].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 \
            "timestamps" not in report['reporting_period'].keys() or len(report['reporting_period']['timestamps']) == 0:
        filename = str(uuid.uuid4()) + '.xlsx'
        wb.save(filename)

        return filename

    ###############################

    has_names_data_flag = True

    if "names" not in report['reporting_period'].keys() or len(
            report['reporting_period']['names']) == 0:
        has_names_data_flag = False

    current_row_number = 6
    if has_names_data_flag:
        reporting_period_data = report['reporting_period']
        category = reporting_period_data['names']
        ca_len = len(category)

        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)].border = f_border

        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] + "/H)"

        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)] = '平均负荷'

        for i in range(0, ca_len):
            col = chr(ord('C') + i)
            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['averages'][i], 2) \
                if reporting_period_data['averages'][i] is not None else 'N/A'

        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)] = '单位面积值'

        for i in range(0, ca_len):
            col = chr(ord('C') + i)
            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['averages_per_unit_area'][i], 2) \
                if reporting_period_data['averages_per_unit_area'][i] is not None else 'N/A'

        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)] = '环比'

        for i in range(0, ca_len):
            col = chr(ord('C') + i)
            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['averages_increment_rate'][i] * 100, 2)) + "%" \
                if reporting_period_data['averages_increment_rate'][i] is not None else "-"

        current_row_number += 2

        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)].border = f_border
        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] + "/H)"

        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)] = '最大负荷'

        for i in range(0, ca_len):
            col = chr(ord('C') + i)
            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['maximums'][i], 2) \
                if reporting_period_data['maximums'][i] is not None else 'N/A'

        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)] = '单位面积值'

        for i in range(0, ca_len):
            col = chr(ord('C') + i)
            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['maximums_per_unit_area'][i], 2) \
                if reporting_period_data['maximums_per_unit_area'][i] is not None else 'N/A'

        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)] = '环比'

        for i in range(0, ca_len):
            col = chr(ord('C') + i)
            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['maximums_increment_rate'][i] * 100, 2)) + "%" \
                if reporting_period_data['maximums_increment_rate'][i] is not None else "-"

        current_row_number += 2

        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)].border = f_border
        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]

        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)] = '负荷系数'

        for i in range(0, ca_len):
            col = chr(ord('C') + i)
            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['factors'][i], 2) \
                if reporting_period_data['factors'][i] is not None else '-'

        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)] = '环比'

        for i in range(0, ca_len):
            col = chr(ord('C') + i)
            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['factors_increment_rate'][i] * 100, 2)) + "%" \
                if reporting_period_data['factors_increment_rate'][i] is not None else "-"

        current_row_number += 2

    has_sub_averages_data_flag = True
    has_sub_maximums_data_flag = True

    if "sub_averages" not in report['reporting_period'].keys() or len(
            report['reporting_period']['sub_averages']) == 0:
        has_sub_averages_data_flag = False

    if "sub_averages" not in report['reporting_period'].keys() or len(
            report['reporting_period']['sub_averages']) == 0:
        has_sub_maximums_data_flag = False

    if has_sub_averages_data_flag or has_sub_maximums_data_flag:
        reporting_period_data = report['reporting_period']
        category = reporting_period_data['names']
        ca_len = len(category)
        times = reporting_period_data['timestamps']
        time = times[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_number = current_row_number
        current_row_number += real_timestamps_len * 7

        if has_sub_averages_data_flag:
            current_row_number = (current_row_number + ca_len * 6)
        if has_sub_maximums_data_flag:
            current_row_number = (current_row_number + ca_len * 6)

        table_start_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):
            if has_sub_averages_data_flag:
                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] + "/H)"
                col = chr(ord(col) + 1)

            if has_sub_maximums_data_flag:
                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] + "/H)"
                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):

                if has_sub_averages_data_flag:
                    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['sub_averages'][j][i], 2) \
                        if reporting_period_data['sub_averages'][j][i] is not None else 0.00
                    col = chr(ord(col) + 1)

                if has_sub_maximums_data_flag:
                    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['sub_maximums'][j][i], 2) \
                        if reporting_period_data['sub_maximums'][j][i] is not None else 0.00
                    col = chr(ord(col) + 1)

            current_row_number += 1

        table_end_number = current_row_number - 1

        current_chart_col_number = 3
        current_chart_row_number = chart_start_number

        for i in range(0, ca_len):
            labels = Reference(ws,
                               min_col=2,
                               min_row=table_start_number + 1,
                               max_row=table_end_number)

            if has_sub_averages_data_flag:
                line = LineChart()
                line.title = '报告期 平均负荷 - ' + ws.cell(
                    column=current_chart_col_number,
                    row=table_start_number).value
                datas = Reference(ws,
                                  min_col=current_chart_col_number,
                                  min_row=table_start_number,
                                  max_row=table_end_number)
                line.add_data(datas, 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
                ws.add_chart(line, "B" + str(current_chart_row_number))
                current_chart_row_number += 6
                current_chart_col_number += 1

            if has_sub_maximums_data_flag:
                line = LineChart()
                line.title = '报告期 最大负荷 - ' + ws.cell(
                    column=current_chart_col_number,
                    row=table_start_number).value
                datas = Reference(ws,
                                  min_col=current_chart_col_number,
                                  min_row=table_start_number,
                                  max_row=table_end_number)
                line.add_data(datas, 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
                ws.add_chart(line, "B" + str(current_chart_row_number))
                current_chart_row_number += 6
                current_chart_col_number += 1
    ##########################################
    current_sheet_parameters_row_number = current_chart_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 = '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
Example #28
0
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 = '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 = decimal_to_column(
                column_to_decimal(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 = decimal_to_column(column_to_decimal(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 = decimal_to_column(
                column_to_decimal(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
Example #29
0
datas = [dut1, dut2]
file_names = ["dut1", "dut2"]
for index, data in enumerate(datas):
    wb = Workbook()
    ws = wb.active
    for row_index in range(1, len(pin_list) + 1):
        ws.cell(row=row_index + 1, column=1).value = pin_list[row_index - 1]

    for row_index in range(len(data)):
        for column_index in range(1, len(data[0]) + 1):
            ws.cell(row=row_index + 1, column=column_index + 1).value = data[row_index][
                column_index - 1
            ]

    categories = Reference(ws, min_row=2, min_col=1, max_row=ws.max_row, max_col=2)
    values = Reference(
        ws, min_row=1, min_col=2, max_row=ws.max_row, max_col=ws.max_column
    )

    chart = LineChart()
    # chart.legend = None
    chart.legend.position = "b"
    chart.title = file_names[index]
    chart.height = 10
    chart.width = 20
    chart.add_data(values, titles_from_data=True)
    chart.set_categories(categories)
    chart.y_axis.title = "ps"
    chart.y_axis.scaling.max = 80
    chart.y_axis.scaling.min = 0
Example #30
0
import os

os.chdir('/storage/emulated/0/ds')
print(os.getcwd())

from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference

workbook = Workbook()
sheet = workbook.active

# Let's create some sample sales data
rows = [["Product", "Online", "Store"], [1, 30, 45], [2, 40, 30], [3, 40, 25],
        [4, 50, 30], [5, 30, 25], [6, 25, 35], [7, 20, 40]]

for row in rows:
    sheet.append(row)
chart = BarChart()
data = Reference(worksheet=sheet, min_row=1, max_row=8, min_col=2, max_col=3)
chart.add_data(data, titles_from_data=True)
sheet.add_chart(chart, "E2")

workbook.save("chart.xlsx")