def create_team_sheet(xlsx_workbook, team_name):
    blank_team_sheet = xlsx_workbook.get_sheet_by_name('Team Sheet')
    decision_sheet = xlsx_workbook.get_sheet_by_name('Decision Sheet')

    # find an opening in the decision sheet for this team's data
    dest_cell = '%s1' % get_column_letter( decision_sheet.max_column+1)
        
    team_sheet = xlsx_workbook.copy_worksheet(blank_team_sheet)
    team_sheet.title = team_name
    team_sheet['A1'] = team_name
    
    # Define start Range(target_start) in the new Worksheet
    min_col, min_row, max_col, max_row = range_boundaries(dest_cell)

    source_range = 'D1:E30'
    
    for row, row_cells in enumerate(decision_sheet[source_range], min_row):
        for column, cell in enumerate(row_cells, min_col):
            cell_value = cell.value
            if cell_value is not None:
                cell_value = cell_value.replace('Team 1', team_name)
                cell_value = cell_value.replace('Team Sheet', team_name)
                
                if cell_value.startswith('=PRODUCT'):
                    frags = cell_value.split(',')
                    frags[1] = frags[1].replace('D', get_column_letter(column-1))
                    cell_value = ','.join(frags)
                    
                if cell_value.startswith('=SUM'):
                    cell_value = cell_value.replace('E', get_column_letter(column) )
            
            decision_sheet.cell(row=row, column=column).value = cell_value
            decision_sheet.cell(row=row, column=column).fill = copy(cell.fill)
            
    return team_sheet
Example #2
0
    def set_number_format( _worksheet, _table_begin_cell, _table_end_cell, _number_formats, _has_header = False ):

        begin_column = _worksheet[_table_begin_cell].column
        begin_column_index = column_index_from_string(begin_column)
        begin_row = _worksheet[_table_begin_cell].row
        end_column = _worksheet[_table_end_cell].column
        end_column_index = column_index_from_string(end_column)
        end_row = _worksheet[_table_end_cell].row

        # print("begin: " + begin_column + ", index: " + str(begin_column_index) + ", row: " + str(begin_row))
        # print("end: " + end_column + ", index: " + str(end_column_index) + ", row: " + str(end_row))

        styling_header = _has_header
        styling_first_table_row = True
        styling_index = 0
        styling_max_column = end_column_index - begin_column_index

        for table_row in range(begin_row, end_row+1):
            if styling_header:
                styling_header = False
                continue

            for table_col in range(begin_column_index, end_column_index+1):
                cell = _worksheet.cell(column=table_col, row=table_row)
                cell.number_format = _number_formats[get_column_letter(table_col)]
Example #3
0
def _getExcelCellName(col, row):
    """Returns the excel cell name for a row and column (zero-indexed)

    >>> _getExcelCellName(0,0)
    'A1'
    >>> _getExcelCellName(2,1)
    'C2'
    """
    # BEWARE - openpyxl uses indexing at 1, to fit with Excel
    return "%s%i" % (get_column_letter(col + 1), row + 1)
Example #4
0
    def set_col_widths(self):
        from openpyxl.utils.cell import get_column_letter
        from openpyxl.cell import Cell
        TYPE_STRING = Cell.TYPE_STRING

        for idx, width in sorted(self._col_widths.iteritems()):
            letter = get_column_letter(idx + 1)
            self.sheet.column_dimensions[letter].width = 1 + min(width, 50)
        for row in self._rows:
            values = []
            for val in row:
                if val:
                    value = val.value
                    cell = Cell(self.sheet, column='A', row=1)
                    if isinstance(value, basestring):
                        cell.set_explicit_value(value, data_type=TYPE_STRING)
                    else:
                        cell.value = value
                    cell.style = val.style
                else:
                    cell = val
                values.append(cell)
            self.sheet.append(values)
        self._rows[:] = ()
Example #5
0
 def get_cell_value(self, row, col):
     col_letter = get_column_letter(col)
     return self.ws[str(col_letter) + str(row)].value
Example #6
0
 def set_column_width(self, dimension_width_list):
     col=1
     for col_width in dimension_width_list:
         if col_width is not None:
             self.ws.column_dimensions[get_column_letter(col)].width = col_width
         col+=1
Example #7
0
print(excel_file.sheetnames)

excel_file.remove(excel_file["Sheet"])

excel_file.remove(excel_file["Sheet"])

sheet1 = excel_file.create_sheet(index=0, title="Column")

sheet2 = excel_file.create_sheet(index=0, title="매출표")

print(excel_file.sheetnames)

for col in sheet1.iter_cols(min_col=1, max_col=6, min_row=1, max_row=3):
    for each_cell in col:
        each_cell.value = utils.get_column_letter(each_cell.column)
        each_cell.alignment = Alignment(horizontal="right", vertical="center")

        each_cell.font = Font(
            bold=True, name="Arial", size=12, underline="single", color="1bb638"
        )

for col in sheet2.iter_cols(min_col=1, max_col=6, min_row=1, max_row=3):

    for each_cell in col:
        each_cell.value = utils.get_column_letter(each_cell)

        each_cell.alignment = Alignment(horizontal="right", vertical="center")

        each_cell.font = Font(italic=True, name="Consoras", size=10, color="ff0000")
Example #8
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" not in report.keys() or \
            "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0:
        filename = str(uuid.uuid4()) + '.xlsx'
        wb.save(filename)

        return filename

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

    reporting_period_data = report['reporting_period']

    has_cost_data_flag = True

    if "names" not in reporting_period_data.keys() or \
            reporting_period_data['names'] is None or \
            len(reporting_period_data['names']) == 0:
        has_cost_data_flag = False

    if has_cost_data_flag:
        ws['B6'].font = title_font
        ws['B6'] = name + ' 报告期成本'

        category = reporting_period_data['names']
        ca_len = len(category)

        ws.row_dimensions[7].height = 60
        ws['B7'].fill = table_fill
        ws['B7'].border = f_border

        ws['B8'].font = title_font
        ws['B8'].alignment = c_c_alignment
        ws['B8'] = '成本'
        ws['B8'].border = f_border

        ws['B9'].font = title_font
        ws['B9'].alignment = c_c_alignment
        ws['B9'] = '单位面积值'
        ws['B9'].border = f_border

        ws['B10'].font = title_font
        ws['B10'].alignment = c_c_alignment
        ws['B10'] = '环比'
        ws['B10'].border = f_border

        col = ''

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

            ws[col + '7'].fill = table_fill
            ws[col + '7'].font = name_font
            ws[col + '7'].alignment = c_c_alignment
            ws[col + '7'] = reporting_period_data['names'][
                i] + " (" + reporting_period_data['units'][i] + ")"
            ws[col + '7'].border = f_border

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

            ws[col + '9'].font = name_font
            ws[col + '9'].alignment = c_c_alignment
            ws[col + '9'] = round(
                reporting_period_data['subtotals_per_unit_area'][i], 2)
            ws[col + '9'].border = f_border

            ws[col + '10'].font = name_font
            ws[col + '10'].alignment = c_c_alignment
            ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \
                if reporting_period_data['increment_rates'][i] is not None else "-"
            ws[col + '10'].border = f_border

        col = chr(ord(col) + 1)

        ws[col + '7'].fill = table_fill
        ws[col + '7'].font = name_font
        ws[col + '7'].alignment = c_c_alignment
        ws[col + '7'] = "总计 (" + reporting_period_data['total_unit'] + ")"
        ws[col + '7'].border = f_border

        ws[col + '8'].font = name_font
        ws[col + '8'].alignment = c_c_alignment
        ws[col + '8'] = round(reporting_period_data['total'], 2)
        ws[col + '8'].border = f_border

        ws[col + '9'].font = name_font
        ws[col + '9'].alignment = c_c_alignment
        ws[col + '9'] = round(reporting_period_data['total_per_unit_area'], 2)
        ws[col + '9'].border = f_border

        ws[col + '10'].font = name_font
        ws[col + '10'].alignment = c_c_alignment
        ws[col + '10'] = str(round(reporting_period_data['total_increment_rate'] * 100, 2)) + "%" \
            if reporting_period_data['total_increment_rate'] is not None else "-"
        ws[col + '10'].border = f_border

    else:
        for i in range(6, 10 + 1):
            ws.row_dimensions[i].height = 0.1

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

    has_ele_peak_flag = True
    if "toppeaks" not in reporting_period_data.keys() or \
            reporting_period_data['toppeaks'] is None or \
            len(reporting_period_data['toppeaks']) == 0:
        has_ele_peak_flag = False

    if has_ele_peak_flag:
        ws['B12'].font = title_font
        ws['B12'] = name + ' 分时用电成本'

        ws.row_dimensions[13].height = 60
        ws['B13'].fill = table_fill
        ws['B13'].font = name_font
        ws['B13'].alignment = c_c_alignment
        ws['B13'].border = f_border

        ws['C13'].fill = table_fill
        ws['C13'].font = name_font
        ws['C13'].alignment = c_c_alignment
        ws['C13'].border = f_border
        ws['C13'] = '分时用电成本'

        ws['B14'].font = title_font
        ws['B14'].alignment = c_c_alignment
        ws['B14'] = '尖'
        ws['B14'].border = f_border

        ws['C14'].font = title_font
        ws['C14'].alignment = c_c_alignment
        ws['C14'].border = f_border
        ws['C14'] = round(reporting_period_data['toppeaks'][0], 2)

        ws['B15'].font = title_font
        ws['B15'].alignment = c_c_alignment
        ws['B15'] = '峰'
        ws['B15'].border = f_border

        ws['C15'].font = title_font
        ws['C15'].alignment = c_c_alignment
        ws['C15'].border = f_border
        ws['C15'] = round(reporting_period_data['onpeaks'][0], 2)

        ws['B16'].font = title_font
        ws['B16'].alignment = c_c_alignment
        ws['B16'] = '平'
        ws['B16'].border = f_border

        ws['C16'].font = title_font
        ws['C16'].alignment = c_c_alignment
        ws['C16'].border = f_border
        ws['C16'] = round(reporting_period_data['midpeaks'][0], 2)

        ws['B17'].font = title_font
        ws['B17'].alignment = c_c_alignment
        ws['B17'] = '谷'
        ws['B17'].border = f_border

        ws['C17'].font = title_font
        ws['C17'].alignment = c_c_alignment
        ws['C17'].border = f_border
        ws['C17'] = round(reporting_period_data['offpeaks'][0], 2)

        pie = PieChart()
        pie.title = name + '分时用电成本'
        labels = Reference(ws, min_col=2, min_row=14, max_row=17)
        pie_data = Reference(ws, min_col=3, min_row=13, max_row=17)
        pie.add_data(pie_data, titles_from_data=True)
        pie.set_categories(labels)
        pie.height = 7.25
        pie.width = 9
        s1 = pie.series[0]
        s1.dLbls = DataLabelList()
        s1.dLbls.showCatName = False
        s1.dLbls.showVal = True
        s1.dLbls.showPercent = True

        ws.add_chart(pie, "D13")

    else:
        for i in range(12, 18 + 1):
            ws.row_dimensions[i].height = 0.1

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

    current_row_number = 19

    has_subtotals_data_flag = True

    if 'subtotals' not in reporting_period_data.keys() or \
            reporting_period_data['subtotals'] is None:
        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

        category = reporting_period_data['names']
        ca_len = len(category)

        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] + \
                ' (' + reporting_period_data['units'][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)] = round(
                reporting_period_data['subtotals'][i], 3)
            ws['C' + str(current_row_number)].border = f_border

            current_row_number += 1

        table_end_row_number = current_row_number - 1

        pie = PieChart()
        pie.title = name + ' 成本占比'
        labels = Reference(ws,
                           min_col=2,
                           min_row=table_start_row_number + 1,
                           max_row=table_end_row_number)
        pie_data = Reference(ws,
                             min_col=3,
                             min_row=table_start_row_number,
                             max_row=table_end_row_number)
        pie.add_data(pie_data, titles_from_data=True)
        pie.set_categories(labels)
        pie.height = 6.6
        pie.width = 9
        s1 = pie.series[0]
        s1.dLbls = DataLabelList()
        s1.dLbls.showCatName = False
        s1.dLbls.showVal = True
        s1.dLbls.showPercent = True

        ws.add_chart(pie, 'D' + str(table_start_row_number))

        if ca_len < 4:
            current_row_number = current_row_number - ca_len + 4

        current_row_number += 1

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

    reporting_period_data = report['reporting_period']
    times = reporting_period_data['timestamps']
    has_detail_data_flag = True
    ca_len = len(report['reporting_period']['names'])
    real_timestamps_len = timestamps_data_not_equal_0(
        report['parameters']['timestamps'])
    table_row = (current_row_number + 1) + ca_len * 6 + real_timestamps_len * 7
    current_end_row_number = (current_row_number + 1) + ca_len * 6 + len(
        times[0]) + 3 + real_timestamps_len * 7
    if "timestamps" not in reporting_period_data.keys() or \
            reporting_period_data['timestamps'] is None or \
            len(reporting_period_data['timestamps']) == 0:
        has_detail_data_flag = False

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

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

        if has_data:
            for i in range(0, len(time)):
                col = 'B'
                row = str(table_row + 1 + i)
                ws[col + row].font = title_font
                ws[col + row].alignment = c_c_alignment
                ws[col + row] = time[i]
                ws[col + row].border = f_border

            for i in range(0, ca_len):

                col = chr(ord('C') + i)

                ws[col + str(table_row)].fill = table_fill
                ws[col + str(table_row)].font = title_font
                ws[col + str(table_row)].alignment = c_c_alignment
                ws[col + str(table_row)] = reporting_period_data['names'][
                    i] + " (" + reporting_period_data['units'][i] + ")"
                ws[col + str(table_row)].border = f_border

                # 39 data
                time = times[i]
                time_len = len(time)

                for j in range(0, time_len):
                    row = str(table_row + 1 + j)
                    ws[col + row].font = title_font
                    ws[col + row].alignment = c_c_alignment
                    ws[col + row] = round(
                        reporting_period_data['values'][i][j], 2)
                    ws[col + row].border = f_border

                line = LineChart()
                line.title = \
                    '报告期成本 - ' + reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
                labels = Reference(ws,
                                   min_col=2,
                                   min_row=table_row + 1,
                                   max_row=max_row)
                line_data = Reference(ws,
                                      min_col=3 + i,
                                      min_row=table_row,
                                      max_row=max_row)
                line.add_data(line_data, titles_from_data=True)
                line.set_categories(labels)
                line_data = line.series[0]
                line_data.marker.symbol = "circle"
                line_data.smooth = True
                line.x_axis.crosses = 'min'
                line.height = 8.25
                line.width = 24
                line.dLbls = DataLabelList()
                line.dLbls.dLblPos = 't'
                line.dLbls.showVal = True
                line.dLbls.showPercent = False
                chart_col = 'B'
                chart_cell = chart_col + str(current_row_number + 1 + 6 * i)
                table_start_draw_flag = current_row_number
                ws.add_chart(line, chart_cell)

            row = str(max_row + 1)

            ws['B' + row].font = title_font
            ws['B' + row].alignment = c_c_alignment
            ws['B' + row] = '小计'
            ws['B' + row].border = f_border

            col = ''

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

            col = chr(ord(col) + 1)

            ws[col + str(table_row)].fill = table_fill
            ws[col + str(table_row)].font = title_font
            ws[col + str(table_row)].alignment = c_c_alignment
            ws[col +
               str(table_row
                   )] = '总计 (' + report['reporting_period']['total_unit'] + ')'
            ws[col + str(table_row)].border = f_border

            total_sum = 0

            for j in range(0, len(time)):
                row = str(table_row + 1 + j)
                ws[col + row].font = title_font
                ws[col + row].alignment = c_c_alignment
                every_day_sum = reporting_period_values_every_day_sum(
                    reporting_period_data, j, ca_len)
                total_sum += every_day_sum
                ws[col + row] = round(every_day_sum, 2)
                ws[col + row].border = f_border

            row = str(table_row + 1 + len(time))
            ws[col + row].font = title_font
            ws[col + row].alignment = c_c_alignment
            ws[col + row] = round(total_sum, 2)
            ws[col + row].border = f_border

        current_row_number = current_end_row_number

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

    has_child_flag = True

    if "child_space" not in report.keys() or "energy_category_names" not in report['child_space'].keys() or \
            len(report['child_space']["energy_category_names"]) == 0 \
            or 'child_space_names_array' not in report['child_space'].keys() \
            or report['child_space']['energy_category_names'] is None \
            or len(report['child_space']['child_space_names_array']) == 0 \
            or len(report['child_space']['child_space_names_array'][0]) == 0:
        has_child_flag = False

    if has_child_flag:
        child = report['child_space']

        ws['B' + str(current_row_number)].font = title_font
        ws['B' + str(current_row_number)] = name + ' 子空间数据'

        current_row_number += 1
        table_start_row_number = current_row_number

        ws.row_dimensions[current_row_number].height = 60
        ws['B' + str(current_row_number)].fill = table_fill
        ws['B' + str(current_row_number)].font = name_font
        ws['B' + str(current_row_number)].alignment = c_c_alignment
        ws['B' + str(current_row_number)].border = f_border
        ws['B' + str(current_row_number)] = '子空间'
        ca_len = len(child['energy_category_names'])

        col = ''

        for i in range(0, ca_len):
            col = chr(ord('C') + i)
            ws[col + str(current_row_number)].fill = table_fill
            ws[col + str(current_row_number)].font = 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)] = child['energy_category_names'][
                i] + ' (' + child['units'][i] + ')'

        col = chr(ord(col) + 1)
        ws[col + str(current_row_number)].fill = table_fill
        ws[col + str(current_row_number)].font = 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
               )] = '总计 (' + report['reporting_period']['total_unit'] + ')'

        space_len = len(child['child_space_names_array'][0])

        for i in range(0, space_len):
            current_row_number += 1
            row = str(current_row_number)

            ws['B' + row].font = title_font
            ws['B' + row].alignment = c_c_alignment
            ws['B' + row] = child['child_space_names_array'][0][i]
            ws['B' + row].border = f_border

            col = ''
            every_day_sum = 0

            for j in range(0, ca_len):
                col = chr(ord('C') + j)
                ws[col + row].font = name_font
                ws[col + row].alignment = c_c_alignment
                every_day_sum += child['subtotals_array'][j][i]
                ws[col + row] = round(child['subtotals_array'][j][i], 2)
                ws[col + row].border = f_border

            col = chr(ord(col) + 1)
            ws[col + row].font = name_font
            ws[col + row].alignment = c_c_alignment
            ws[col + row] = round(every_day_sum, 2)
            ws[col + row].border = f_border

        table_end_row_number = current_row_number
        current_row_number += 1
        chart_start_row_number = current_row_number

        # Pie
        for i in range(0, ca_len):
            pie = PieChart()
            labels = Reference(ws,
                               min_col=2,
                               min_row=table_start_row_number + 1,
                               max_row=table_end_row_number)
            pie_data = Reference(ws,
                                 min_col=3 + i,
                                 min_row=table_start_row_number,
                                 max_row=table_end_row_number)
            pie.add_data(pie_data, titles_from_data=True)
            pie.set_categories(labels)
            pie.height = 6.6
            pie.width = 8
            pie.title = ws.cell(column=3 + i, row=table_start_row_number).value
            s1 = pie.series[0]
            s1.dLbls = DataLabelList()
            s1.dLbls.showCatName = False
            s1.dLbls.showVal = True
            s1.dLbls.showPercent = True
            chart_cell = ''
            if i % 2 == 0:
                chart_cell = 'B' + str(chart_start_row_number)
            else:
                chart_cell = 'E' + str(chart_start_row_number)
                chart_start_row_number += 5
            ws.add_chart(pie, chart_cell)

        current_row_number = chart_start_row_number

        if ca_len % 2 == 1:
            current_row_number += 5

        current_row_number += 1
    ##########################################
    current_sheet_parameters_row_number = table_start_draw_flag + ca_len * 6 + 1
    has_parameters_names_and_timestamps_and_values_data = True
    if 'parameters' not in report.keys() or \
            report['parameters'] is None or \
            'names' not in report['parameters'].keys() or \
            report['parameters']['names'] is None or \
            len(report['parameters']['names']) == 0 or \
            'timestamps' not in report['parameters'].keys() or \
            report['parameters']['timestamps'] is None or \
            len(report['parameters']['timestamps']) == 0 or \
            'values' not in report['parameters'].keys() or \
            report['parameters']['values'] is None or \
            len(report['parameters']['values']) == 0 or \
            timestamps_data_all_equal_0(report['parameters']['timestamps']):
        has_parameters_names_and_timestamps_and_values_data = False
    if has_parameters_names_and_timestamps_and_values_data:

        ###############################
        # new worksheet
        ###############################

        parameters_data = report['parameters']
        parameters_names_len = len(parameters_data['names'])

        parameters_ws = wb.create_sheet('相关参数')

        parameters_timestamps_data_max_len = \
            get_parameters_timestamps_lists_max_len(list(parameters_data['timestamps']))

        # Row height
        parameters_ws.row_dimensions[1].height = 102
        for i in range(2, 7 + 1):
            parameters_ws.row_dimensions[i].height = 42

        for i in range(8, parameters_timestamps_data_max_len + 10):
            parameters_ws.row_dimensions[i].height = 60

        # Col width
        parameters_ws.column_dimensions['A'].width = 1.5

        parameters_ws.column_dimensions['B'].width = 25.0

        for i in range(3, 12 + parameters_names_len * 3):
            parameters_ws.column_dimensions[format_cell.get_column_letter(
                i)].width = 15.0

        # Img
        img = Image("excelexporters/myems.png")
        img.width = img.width * 0.85
        img.height = img.height * 0.85
        # img = Image("myems.png")
        parameters_ws.add_image(img, 'B1')

        # Title
        parameters_ws.row_dimensions[3].height = 60

        parameters_ws['B3'].font = name_font
        parameters_ws['B3'].alignment = b_r_alignment
        parameters_ws['B3'] = 'Name:'
        parameters_ws['C3'].border = b_border
        parameters_ws['C3'].alignment = b_c_alignment
        parameters_ws['C3'].font = name_font
        parameters_ws['C3'] = name

        parameters_ws['D3'].font = name_font
        parameters_ws['D3'].alignment = b_r_alignment
        parameters_ws['D3'] = 'Period:'
        parameters_ws['E3'].border = b_border
        parameters_ws['E3'].alignment = b_c_alignment
        parameters_ws['E3'].font = name_font
        parameters_ws['E3'] = period_type

        parameters_ws['F3'].font = name_font
        parameters_ws['F3'].alignment = b_r_alignment
        parameters_ws['F3'] = 'Date:'
        parameters_ws['G3'].border = b_border
        parameters_ws['G3'].alignment = b_c_alignment
        parameters_ws['G3'].font = name_font
        parameters_ws[
            'G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local
        parameters_ws.merge_cells("G3:H3")

        parameters_ws_current_row_number = 6

        parameters_ws['B' +
                      str(parameters_ws_current_row_number)].font = title_font
        parameters_ws['B' +
                      str(parameters_ws_current_row_number)] = name + ' 相关参数'

        parameters_ws_current_row_number += 1

        parameters_table_start_row_number = parameters_ws_current_row_number

        parameters_ws.row_dimensions[
            parameters_ws_current_row_number].height = 80

        parameters_ws_current_row_number += 1

        table_current_col_number = '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 #9
0
def set_column_width(sheet, start_column, widthes):
    start_column_idx = column_index_from_string(start_column)

    for index in range(len(widthes)):
        column_letter = get_column_letter(start_column_idx + index)
        sheet.column_dimensions[column_letter].width = widthes[index]
Example #10
0
spread.share('*****@*****.**', perm_type='user', role='owner')

#data_path = 'C:\\python\\examples\\2.4\\data'
data_path = './'
file_list = os.listdir(data_path)

for fname in file_list:
    if fname[-4:] != 'xlsx':
        continue
    file_path = os.path.join(data_path, fname)
    wb = load_workbook(file_path, read_only=True)
    ws = wb.active
    row_count = ws.max_row
    col_count = ws.max_column

    worksheet = spread.add_worksheet(fname, row_count, col_count)
    cells = worksheet.range('A1:' + get_column_letter(col_count) + str(row_count))

    idx = 0
    for row in ws.iter_rows():
        for cell in row:
            cells[idx].value = str(cell.value)
            idx = idx + 1

    worksheet.update_cells(cells)

#spread.share('직원[email protected]', perm_type='user', role='reader')
#spread.share('직원[email protected]', perm_type='user', role='writer')
#spread.share('직원[email protected]', perm_type='user', role='reader')

        for j in range(1, 23):
            wb[country].cell(row=row,
                             column=j).value = rawsheet.cell(row=i,
                                                             column=1).value
            wb[country].cell(row=row, column=j).hyperlink = rawsheet.cell(
                row=i, column=1).hyperlink

            i += 1
        row += 1

    for j in range(1, 23):
        for i in range(1, int(rows / 22 + 1)):

            cell_length = len(as_text(wb[country].cell(row=i, column=j).value))
            if cell_length > max_len:
                wb[country].column_dimensions[get_column_letter(
                    j)].width = cell_length
                max_len = cell_length
            else:
                wb[country].column_dimensions[get_column_letter(
                    j)].width = max_len

    wb[country].delete_cols(1)

    wb.save(master_sheet)
    print(country + " Done.")

end = time.time()

exec_time = end - start
print("\n\t\t Execution Time : ", exec_time, "\n")
Example #12
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
    # 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

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

    has_cost_data_flag = True

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

    if has_cost_data_flag:
        ws['B6'].font = title_font
        ws['B6'] = name + '报告期成本'

        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'] = '成本'
        ws['B8'].border = f_border

        ws['B9'].font = title_font
        ws['B9'].alignment = c_c_alignment
        ws['B9'] = '环比'
        ws['B9'].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'] = 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.rows_dimensions[i].height = 0.1

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

    has_cost_datail_flag = True
    reporting_period_data = report['reporting_period']
    category = report['meter']['energy_category_name']
    ca_len = len(category)
    times = 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

    if "values" not in reporting_period_data.keys() or len(
            reporting_period_data['values']) == 0:
        has_cost_datail_flag = False

    if has_cost_datail_flag:
        start_detail_data_row_number = 13 + (parameters_parameters_datas_len +
                                             ca_len) * 6

        ws['B11'].font = title_font
        ws['B11'] = name + '详细数据'

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

        if has_data:

            end_data_row_number = start_detail_data_row_number

            for i in range(0, len(time)):
                col = 'B'
                end_data_row_number += 1
                row = str(end_data_row_number)

                ws[col + row].font = title_font
                ws[col + row].alignment = c_c_alignment
                ws[col + row] = time[i]
                ws[col + row].border = f_border

            ws['B' + str(end_data_row_number + 1)].font = title_font
            ws['B' + str(end_data_row_number + 1)].alignment = c_c_alignment
            ws['B' + str(end_data_row_number + 1)] = '总计'
            ws['B' + str(end_data_row_number + 1)].border = f_border

            for i in range(0, ca_len):

                col = chr(ord('C') + i)

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

                time = times
                time_len = len(time)

                for j in range(0, time_len):
                    row = str(start_detail_data_row_number + 1 + j)

                    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

                ws[col + str(end_data_row_number + 1)].font = title_font
                ws[col +
                   str(end_data_row_number + 1)].alignment = c_c_alignment
                ws[col + str(end_data_row_number + 1)] = round(
                    reporting_period_data['total_in_category'], 2)
                ws[col + str(end_data_row_number + 1)].border = f_border

            line = LineChart()
            line.title = '报告期成本 - ' + report['meter']['energy_category_name'] + \
                         " (" + report['meter']['unit_of_measure'] + ")"
            line_data = Reference(ws,
                                  min_col=3,
                                  min_row=start_detail_data_row_number,
                                  max_row=max_row)
            line.series.append(Series(line_data, title_from_data=True))
            labels = Reference(ws,
                               min_col=2,
                               min_row=start_detail_data_row_number + 1,
                               max_row=max_row)
            line.set_categories(labels)
            line_data = line.series[0]
            line_data.marker.symbol = "circle"
            line_data.smooth = True
            line.x_axis.crosses = 'min'
            line.dLbls = DataLabelList()
            line.dLbls.dLblPos = 't'
            line.dLbls.showVal = True
            line.height = 8.25
            line.width = 24
            ws.add_chart(line, "B12")
    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
    time_len = len(reporting_period_data['timestamps'])
    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 = '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 #13
0
def Avg3handMax(excelFiles, startStr, indexList, firstbound, secondbound,
                thirdbound, fourthbound, listduplicate):
    # for excelFiles in os.listdir("excel_output"):
    wb = openpyxl.load_workbook("excel_output/" + excelFiles)
    rawdata = wb['Original Data']
    avg_3h = wb['3h Average']
    regionMax = wb['Regional Hour Max']
    everything = wb['Everything Together']
    numberRow = rawdata.max_row
    numberColumn = rawdata.max_column
    regionalMaxcolum = len(indexList) + 2

    rawdata_delta = rawdata.max_column + 1
    regional_delta = regionalMaxcolum + 2

    # creates graph for region max
    # hourly reg max: get_column_letter(len(indexList) + 4) + str(r)

    concentration_data = Reference(regionMax,
                                   min_col=len(indexList) + 4,
                                   min_row=1,
                                   max_row=numberRow)
    dates_data = Reference(regionMax, min_col=1, min_row=2, max_row=numberRow)

    qc24regionmax_chart = ScatterChart()
    qc24regionmax_chart.title = "Quebec Monthly Max Graph"
    qc24regionmax_chart.style = 2
    qc24regionmax_chart.y_axis.title = "Concentration"
    qc24regionmax_chart.x_axis.number_format = 'dd'
    qc24regionmax_chart.x_axis.majorTimeUnit = "days"
    qc24regionmax_chart.x_axis.title = "Date"

    qc24hSeries = Series(concentration_data, dates_data, title_from_data=True)
    qc24regionmax_chart.series.append(qc24hSeries)
    regionMax.add_chart(qc24regionmax_chart,
                        get_column_letter(len(indexList) + 6) + "1")

    for sheets in wb.worksheets:
        sheets.freeze_panes = "C2"
        # copies row/column from old set
        if sheets != wb['Original Data']:
            for r in range(1, numberRow + 1):
                for c in range(1, 3):
                    # write the stations
                    if r is 1:
                        for allC in range(1, numberColumn + 1):

                            # creates the 3h avg station row header
                            if sheets == avg_3h:
                                sheets[get_column_letter(allC) + str(r)] \
                                    = '=(\'Original Data\'!' + get_column_letter(allC) + str(r) + ')'

                        # write region max row header
                        if excelFiles.startswith(startStr):
                            for i, p in enumerate(indexList):
                                if sheets == regionMax:
                                    sheets[get_column_letter(i + 3) +
                                           str(r)] = p

                    # write time and date for both 3h avg and region max sheet
                    if r is 2 or r is 3:
                        for allC in range(3, numberColumn + 1):
                            sheets[get_column_letter(allC) + str(r)] = ''
                    sheets[
                        get_column_letter(c) +
                        str(r)] = '=(\'Original Data\'!' + get_column_letter(
                            c) + str(r) + ')'

        # applies conditional formatting rule
        if excelFiles.startswith(startStr):
            if sheets == everything:
                if startStr == "PM25":
                    addcolor(everything, 2 * rawdata_delta + regional_delta,
                             numberRow, firstbound, secondbound, thirdbound,
                             fourthbound)
                if startStr == ("NO2" or "O3"):
                    addcolor(everything, rawdata_delta + regional_delta,
                             numberRow, firstbound, secondbound, thirdbound,
                             fourthbound)

            if sheets != everything:
                addcolor(sheets, numberColumn, numberRow, firstbound,
                         secondbound, thirdbound, fourthbound)

    # rounds everything to integer
    for i in range(0, numberRow - 3):
        for o in range(3, numberColumn + 1):
            avg_3h[get_column_letter(o) + str(i + 4)] = \
                '=IF((COUNTA(\'Original Data\'!' + get_column_letter(o) + str(i + 2) + ':' + get_column_letter(o) \
                + str(i + 4) + '))>1,ROUND(AVERAGE(\'Original Data\'!' + \
                get_column_letter(o) + str(i + 2) + ':' + get_column_letter(o) + str(i + 4) + '),0),-999)'

    # calculate region max, this one has to be based on 3h avg
    if startStr == "PM25":
        regionMax[get_column_letter(len(indexList) + 4) + '1'] = "Hour QC Max"
        for r in range(4, numberRow + 1):
            for c, data in zip(range(3, len(indexList) + 3), listduplicate):
                sData = data[0] + 3
                endData = data[-1] + 3
                regionMax[get_column_letter(c) + str(r)] = '=MAX(\'3h Average\'!' \
                                                           + get_column_letter(sData) \
                                                           + str(r) + ':' + \
                                                           get_column_letter(endData) \
                                                           + str(r) + ')'
            # for the hourly max, it has to exclude the temis region
            for name in indexList:
                if name == "Temis.":
                    temisLetter = get_column_letter(
                        indexList.index("Temis.") + 3)
                    regionMax[get_column_letter(len(indexList) + 4) + str(r)] \
                        = '=IF(MAX(' + get_column_letter(3) + str(r) + ':' \
                          + get_column_letter(regionalMaxcolum) + str(r) + ')=' \
                          + temisLetter + str(r) + ',LARGE(' + get_column_letter(3) + str(r) + ':' \
                          + get_column_letter(regionalMaxcolum) + str(r) + ',2),MAX(' + get_column_letter(3) + str(
                        r) + ':' \
                          + get_column_letter(regionalMaxcolum) + str(r) + '))'

        # This part of script rewrite all data into one sheet
        for r in range(1, rawdata.max_row + 1):
            for c in range(1, rawdata.max_column + 1):
                # ROUND(\'Original Data\'!' + get_column_letter(c) + str(r) + ',0))
                everything[get_column_letter(c) + str(
                    r
                )] = '=IF((\'Original Data\'!' + get_column_letter(c) + str(
                    r) + ')="",-999,(\'Original Data\'!' + get_column_letter(
                        c) + str(r) + '))'

        # 3h avgs copy
        delta = rawdata.max_column + 1
        for avg_C in range(3, avg_3h.max_column + 1):
            for avg_R in range(1, avg_3h.max_row + 1):
                everything[get_column_letter(avg_C + delta) + str(
                    avg_R
                )] = '=IF((\'3h Average\'!' + get_column_letter(avg_C) + str(
                    avg_R) + ')="",-999,(\'3h Average\'!' + get_column_letter(
                        avg_C) + str(avg_R) + '))'

        # reg hour max copy
        avg3h_delta = avg_3h.max_column
        for reg_C in range(3, len(indexList) + 5):
            for reg_R in range(1, regionMax.max_row + 1):
                everything[get_column_letter(reg_C + delta + avg3h_delta) + str(
                    reg_R
                )] = '=IF((\'Regional Hour Max\'!' + get_column_letter(
                    reg_C
                ) + str(
                    reg_R
                ) + ')="",-999,(\'Regional Hour Max\'!' + get_column_letter(
                    reg_C) + str(reg_R) + '))'

    else:
        # NO2 and O3 are based on direct observation
        # a bit of a hack but 3h avg are not needed for them so I just remove the sheet
        wb.remove_sheet(avg_3h)
        regionMax[get_column_letter(len(indexList) + 4) + '1'] = "Hour QC Max"
        for r in range(2, numberRow + 1):
            for c, data in zip(range(3, len(indexList) + 3), listduplicate):
                sData = data[0] + 3
                endData = data[-1] + 3
                regionMax[get_column_letter(c) + str(r)] = '=MAX(\'Original Data\'!' \
                                                           + get_column_letter(sData) \
                                                           + str(r) + ':' + \
                                                           get_column_letter(endData) \
                                                           + str(r) + ')'
            # for hourly max
            regionMax[get_column_letter(len(indexList) + 4) + str(r)] = '=MAX(' + get_column_letter(3) + str(
                r) + ':' \
                                                                        + get_column_letter(regionalMaxcolum) + str(
                r) + ')'

        # This part of script rewrite all data into one sheet
        for r in range(1, rawdata.max_row + 1):
            for c in range(1, rawdata.max_column + 1):
                everything[get_column_letter(c) + str(
                    r
                )] = '=IF((\'Original Data\'!' + get_column_letter(c) + str(
                    r) + ')="",-999,(\'Original Data\'!' + get_column_letter(
                        c) + str(r) + '))'

        # reg hour max copy
        delta = rawdata.max_column + 1
        for reg_C in range(3, len(indexList) + 5):
            for reg_R in range(1, regionMax.max_row + 1):
                everything[get_column_letter(reg_C + delta) + str(
                    reg_R
                )] = '=IF((\'Regional Hour Max\'!' + get_column_letter(
                    reg_C
                ) + str(
                    reg_R
                ) + ')="",-999,(\'Regional Hour Max\'!' + get_column_letter(
                    reg_C) + str(reg_R) + '))'

    # write daily max for all 3 file
    regionMax[get_column_letter(len(indexList) + 5) + '1'] = "Daily Max"
    for day in range(len(listofDate)):
        for r in range(4, numberRow + 1):
            regionMax[get_column_letter(len(indexList) + 5) +
                      str(2 + day * 24)] = '=MAX(' + get_column_letter(
                          len(indexList) +
                          4) + str(2 + day * 24) + ':' + get_column_letter(
                              len(indexList) + 4) + str(25 + day * 24) + ')'
    # does it for everything sheet
    dailyMaxLetter = get_column_letter(everything.max_column + 1)
    qcHourMaxLetter = get_column_letter(everything.max_column)
    everything[dailyMaxLetter + '1'] = "Daily Max"
    for day in range(len(listofDate)):
        for r in range(4, numberRow + 1):
            everything[dailyMaxLetter +
                       str(2 + day * 24)] = '=MAX(' + qcHourMaxLetter + str(
                           2 + day * 24) + ':' + qcHourMaxLetter + str(
                               25 + day * 24) + ')'
    wb.save("excel_output/" + excelFiles)
Example #14
0
def generate_excel(report,
                   name,
                   reporting_start_datetime_local,
                   reporting_end_datetime_local,
                   period_type):
    wb = Workbook()
    ws = wb.active
    ws.title = "EquipmentIncome"

    # Row height
    ws.row_dimensions[1].height = 102
    for i in range(2, 2000 + 1):
        ws.row_dimensions[i].height = 42

    # Col width
    ws.column_dimensions['A'].width = 1.5

    ws.column_dimensions['B'].width = 25.0

    for i in range(ord('C'), ord('L')):
        ws.column_dimensions[chr(i)].width = 15.0

    # Font
    name_font = Font(name='Arial', size=15, bold=True)
    title_font = Font(name='Arial', size=15, bold=True)

    table_fill = PatternFill(fill_type='solid', fgColor='1F497D')
    f_border = Border(left=Side(border_style='medium', color='00000000'),
                      right=Side(border_style='medium', color='00000000'),
                      bottom=Side(border_style='medium', color='00000000'),
                      top=Side(border_style='medium', color='00000000')
                      )
    b_border = Border(bottom=Side(border_style='medium', color='00000000'), )

    b_c_alignment = Alignment(vertical='bottom',
                              horizontal='center',
                              text_rotation=0,
                              wrap_text=True,
                              shrink_to_fit=False,
                              indent=0)
    c_c_alignment = Alignment(vertical='center',
                              horizontal='center',
                              text_rotation=0,
                              wrap_text=True,
                              shrink_to_fit=False,
                              indent=0)
    b_r_alignment = Alignment(vertical='bottom',
                              horizontal='right',
                              text_rotation=0,
                              wrap_text=True,
                              shrink_to_fit=False,
                              indent=0)

    # Img
    img = Image("excelexporters/myems.png")
    ws.add_image(img, 'A1')

    # Title
    ws['B3'].alignment = b_r_alignment
    ws['B3'] = 'Name:'
    ws['C3'].border = b_border
    ws['C3'].alignment = b_c_alignment
    ws['C3'] = name

    ws['D3'].alignment = b_r_alignment
    ws['D3'] = 'Period:'
    ws['E3'].border = b_border
    ws['E3'].alignment = b_c_alignment
    ws['E3'] = period_type

    ws['B4'].alignment = b_r_alignment
    ws['B4'] = 'Reporting Start Datetime:'
    ws['C4'].border = b_border
    ws['C4'].alignment = b_c_alignment
    ws['C4'] = reporting_start_datetime_local

    ws['D4'].alignment = b_r_alignment
    ws['D4'] = 'Reporting End Datetime:'
    ws['E4'].border = b_border
    ws['E4'].alignment = b_c_alignment
    ws['E4'] = reporting_end_datetime_local

    if "reporting_period" not in report.keys() or \
            "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0:
        filename = str(uuid.uuid4()) + '.xlsx'
        wb.save(filename)

        return filename

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

    reporting_period_data = report['reporting_period']

    has_cost_data_flag = True

    if "names" not in reporting_period_data.keys() or \
            reporting_period_data['names'] is None or \
            len(reporting_period_data['names']) == 0:
        has_cost_data_flag = False

    if has_cost_data_flag:
        ws['B5'].font = title_font
        ws['B5'] = name + ' ' + 'Reporting Period Income'
        category = reporting_period_data['names']
        ca_len = len(category)

        ws.row_dimensions[7].height = 60
        ws['B6'].fill = table_fill
        ws['B6'].border = f_border

        ws['B7'].font = title_font
        ws['B7'].alignment = c_c_alignment
        ws['B7'] = 'Reporting Period Income'
        ws['B7'].border = f_border

        ws['B8'].font = title_font
        ws['B8'].alignment = c_c_alignment
        ws['B8'] = 'Increment Rate'
        ws['B8'].border = f_border

        col = ''

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

            ws[col + '6'].fill = table_fill
            ws[col + '6'].font = name_font
            ws[col + '6'].alignment = c_c_alignment
            ws[col + '6'] = reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
            ws[col + '6'].border = f_border

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

            ws[col + '8'].font = name_font
            ws[col + '8'].alignment = c_c_alignment
            ws[col + '8'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \
                if reporting_period_data['increment_rates'][i] is not None else "-"
            ws[col + '8'].border = f_border

        col = chr(ord(col) + 1)

        ws[col + '6'].fill = table_fill
        ws[col + '6'].font = name_font
        ws[col + '6'].alignment = c_c_alignment
        ws[col + '6'] = "Total (" + reporting_period_data['total_unit'] + ")"
        ws[col + '6'].border = f_border

        ws[col + '7'].font = name_font
        ws[col + '7'].alignment = c_c_alignment
        ws[col + '7'] = round(reporting_period_data['total'], 2)
        ws[col + '7'].border = f_border

        ws[col + '8'].font = name_font
        ws[col + '8'].alignment = c_c_alignment
        ws[col + '8'] = str(round(reporting_period_data['total_increment_rate'] * 100, 2)) + "%" \
            if reporting_period_data['total_increment_rate'] is not None else "-"
        ws[col + '8'].border = f_border

    else:
        for i in range(6, 8 + 1):
            ws.row_dimensions[i].height = 0.1
    ####################################################################################################################
    current_row_number = 10
    has_subtotals_data_flag = True
    if "subtotals" not in reporting_period_data.keys() or \
            reporting_period_data['subtotals'] is None or \
            len(reporting_period_data['subtotals']) == 0:
        has_subtotals_data_flag = False

    if has_subtotals_data_flag:
        ws['B' + str(current_row_number)].font = title_font
        ws['B' + str(current_row_number)] = name + ' ' + 'Incomes by Energy Category'

        current_row_number += 1

        table_start_row_number = current_row_number

        ws['B' + str(current_row_number)].fill = table_fill
        ws['B' + str(current_row_number)].font = name_font
        ws['B' + str(current_row_number)].alignment = c_c_alignment
        ws['B' + str(current_row_number)].border = f_border

        ws['C' + str(current_row_number)].fill = table_fill
        ws['C' + str(current_row_number)].font = name_font
        ws['C' + str(current_row_number)].alignment = c_c_alignment
        ws['C' + str(current_row_number)].border = f_border
        ws['C' + str(current_row_number)] = 'Incomes'

        ws['D' + str(current_row_number)].fill = table_fill
        ws['D' + str(current_row_number)].font = name_font
        ws['D' + str(current_row_number)].alignment = c_c_alignment
        ws['D' + str(current_row_number)].border = f_border
        ws['D' + str(current_row_number)] = 'Proportion'

        current_row_number += 1

        ca_len = len(reporting_period_data['names'])
        income_sum = Decimal(0.0)
        for i in range(0, ca_len):
            income_sum = round(reporting_period_data['subtotals'][i], 2) + income_sum
        for i in range(0, ca_len):
            ws['B' + str(current_row_number)].font = title_font
            ws['B' + str(current_row_number)].alignment = c_c_alignment
            ws['B' + str(current_row_number)] = reporting_period_data['names'][i]
            ws['B' + str(current_row_number)].border = f_border

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

            ws['D' + str(current_row_number)].font = title_font
            ws['D' + str(current_row_number)].alignment = c_c_alignment
            ws['D' + str(current_row_number)].border = f_border
            ws['D' + str(current_row_number)] = '{:.2%}'.format(round(
                reporting_period_data['subtotals'][i], 2) / income_sum) \
                if income_sum is not None and income_sum != Decimal(0.0) \
                else ''

            current_row_number += 1

        table_end_row_number = current_row_number - 1

        pie = PieChart()
        pie.title = name + ' ' + 'Incomes by Energy Category'
        labels = Reference(ws, min_col=2, min_row=table_start_row_number + 1, max_row=table_end_row_number)
        pie_data = Reference(ws, min_col=3, min_row=table_start_row_number, max_row=table_end_row_number)
        pie.add_data(pie_data, titles_from_data=True)
        pie.set_categories(labels)
        pie.height = 6.6
        pie.width = 9
        s1 = pie.series[0]
        s1.dLbls = DataLabelList()
        s1.dLbls.showCatName = False
        s1.dLbls.showVal = True
        s1.dLbls.showPercent = True
        table_cell = 'F' + str(table_start_row_number - 1)
        ws.add_chart(pie, table_cell)

        if ca_len < 4:
            current_row_number = current_row_number - ca_len + 4

    else:
        for i in range(13, 22 + 1):
            ws.row_dimensions[i].height = 0.1

    ####################################################################################################################
    current_row_number = 14
    reporting_period_data = report['reporting_period']
    times = reporting_period_data['timestamps']
    has_detail_data_flag = True
    ca_len = len(report['reporting_period']['names'])
    real_timestamps_len = timestamps_data_not_equal_0(report['parameters']['timestamps'])
    table_row = (current_row_number + 1) + ca_len * 6 + real_timestamps_len * 7
    if "timestamps" not in reporting_period_data.keys() or \
            reporting_period_data['timestamps'] is None or \
            len(reporting_period_data['timestamps']) == 0:
        has_detail_data_flag = False

    if has_detail_data_flag:
        ws['B' + str(current_row_number)].font = title_font
        ws['B' + str(current_row_number)] = name + ' ' + 'Detailed Data'

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

        if has_data:
            for i in range(0, len(time)):
                col = 'B'
                row = str(table_row + 1 + i)
                ws[col + row].font = title_font
                ws[col + row].alignment = c_c_alignment
                ws[col + row] = time[i]
                ws[col + row].border = f_border

            for i in range(0, ca_len):

                col = chr(ord('C') + i)

                ws[col + str(table_row)].fill = table_fill
                ws[col + str(table_row)].font = title_font
                ws[col + str(table_row)].alignment = c_c_alignment
                ws[col + str(table_row)] = reporting_period_data['names'][i] + " (" + reporting_period_data['units'][
                    i] + ")"
                ws[col + str(table_row)].border = f_border

                # 39 data
                time = times[i]
                time_len = len(time)

                for j in range(0, time_len):
                    row = str(table_row + 1 + j)
                    ws[col + row].font = title_font
                    ws[col + row].alignment = c_c_alignment
                    ws[col + row] = round(reporting_period_data['values'][i][j], 2)
                    ws[col + row].border = f_border

                line = LineChart()
                line.title = 'Reporting Period Income - ' + reporting_period_data['names'][i] + \
                    " (" + reporting_period_data['units'][i] + ")"
                labels = Reference(ws, min_col=2, min_row=table_row + 1, max_row=max_row)
                line_data = Reference(ws, min_col=3 + i, min_row=table_row, max_row=max_row)
                line.add_data(line_data, titles_from_data=True)
                line.set_categories(labels)
                line_data = line.series[0]
                line_data.marker.symbol = "circle"
                line_data.smooth = True
                line.x_axis.crosses = 'min'
                line.height = 8.25
                line.width = 24
                line.dLbls = DataLabelList()
                line.dLbls.dLblPos = 't'
                line.dLbls.showVal = True
                line.dLbls.showPercent = False
                chart_col = 'B'
                chart_cell = chart_col + str(current_row_number + 1 + 6 * i)
                ws.add_chart(line, chart_cell)

            row = str(max_row + 1)

            ws['B' + row].font = title_font
            ws['B' + row].alignment = c_c_alignment
            ws['B' + row] = 'Subtotal'
            ws['B' + row].border = f_border

            col = ''

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

            col = chr(ord(col) + 1)

            ws[col + str(table_row)].fill = table_fill
            ws[col + str(table_row)].font = title_font
            ws[col + str(table_row)].alignment = c_c_alignment
            ws[col + str(table_row)] = 'Total (' + report['reporting_period']['total_unit'] + ')'
            ws[col + str(table_row)].border = f_border

            total_sum = 0

            for j in range(0, len(time)):
                row = str(table_row + 1 + j)
                ws[col + row].font = title_font
                ws[col + row].alignment = c_c_alignment
                periodic_sum = reporting_period_values_periodic_sum(reporting_period_data, j, ca_len)
                total_sum += periodic_sum
                ws[col + row] = round(periodic_sum, 2)
                ws[col + row].border = f_border

            row = str(table_row + 1 + len(time))
            ws[col + row].font = title_font
            ws[col + row].alignment = c_c_alignment
            ws[col + row] = round(total_sum, 2)
            ws[col + row].border = f_border

    else:
        for i in range(37, 69 + 1):
            ws.row_dimensions[i].height = 0.1
    ####################################################################################################################
    current_sheet_parameters_row_number = current_row_number + ca_len * 6 + 1
    has_parameters_names_and_timestamps_and_values_data = True
    if 'parameters' not in report.keys() or \
            report['parameters'] is None or \
            'names' not in report['parameters'].keys() or \
            report['parameters']['names'] is None or \
            len(report['parameters']['names']) == 0 or \
            'timestamps' not in report['parameters'].keys() or \
            report['parameters']['timestamps'] is None or \
            len(report['parameters']['timestamps']) == 0 or \
            'values' not in report['parameters'].keys() or \
            report['parameters']['values'] is None or \
            len(report['parameters']['values']) == 0 or \
            timestamps_data_all_equal_0(report['parameters']['timestamps']):

        has_parameters_names_and_timestamps_and_values_data = False
    if has_parameters_names_and_timestamps_and_values_data:

        ################################################################################################################
        # new worksheet
        ################################################################################################################

        parameters_data = report['parameters']
        parameters_names_len = len(parameters_data['names'])

        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 #15
0
def add_style_tox(tox_dataframe, PATH):

    wb = load_workbook(PATH)
    ws = wb['Tox']

    nb_rows, nb_columns = tox_dataframe.shape

    thin = Side(border_style='thin', color='FF000000')
    medium = Side(border_style='medium', color='FF000000')
    double = Side(border_style='double', color='FF000000')
    no_border = Side(border_style=None)

    font_Arial9 = Font(size=9, name='Arial')
    font_title = Font(name='Arial', size=10, bold=True, color='FF000000')
    font_small_title = Font(name='Arial', size=8, bold=False, color='FF000000')
    alignment_center = Alignment(horizontal='center', vertical='center')

    ## COLUMN WIDTH ##
    ws.column_dimensions['A'].width = 3
    ws.column_dimensions['B'].width = 12
    ws.column_dimensions['C'].width = 10
    ws.column_dimensions['D'].width = 45
    ws.column_dimensions['E'].width = 14

    ws.row_dimensions[3].height = 45

    # Nettoyage Fin du tableau
    cell = ws['S4']
    cell.border = no_border

    # Nettoyage entre 2 tableaux
    cell = ws['F4']
    cell.border = Border(top=no_border, bottom=no_border)
    ws.column_dimensions['F'].width = 3

    medium_border = Border(left=medium,
                           right=medium,
                           top=medium,
                           bottom=medium)
    normal_cells_border = Border(left=thin, right=thin, top=thin, bottom=thin)
    header_stations_font = Font(size=10,
                                bold=True,
                                name='Arial',
                                color='FFFFFF')
    header_stations_fill = PatternFill(fill_type='solid',
                                       start_color='808080',
                                       end_color='808080')
    center_alignment = Alignment(horizontal='center', vertical='center')

    ## REFORMATAGE STATIONS DATA
    columns_stations = ['B', 'C', 'D', 'E']
    for column in columns_stations:
        for row in range(5, 5 + nb_rows):
            cell = ws[column + str(row)]
            if column == 'B':
                if row == 5 + nb_rows - 1:
                    cell.border = Border(left=medium,
                                         top=thin,
                                         right=thin,
                                         bottom=medium)
                else:
                    cell.border = Border(left=medium,
                                         top=thin,
                                         right=thin,
                                         bottom=thin)
            elif column == 'E':
                if row == 5 + nb_rows - 1:
                    cell.border = Border(left=thin,
                                         top=thin,
                                         right=medium,
                                         bottom=medium)
                else:
                    cell.border = Border(left=thin,
                                         top=thin,
                                         right=medium,
                                         bottom=thin)
            elif row == 5 + nb_rows - 1:
                cell.border = Border(left=thin,
                                     top=thin,
                                     right=thin,
                                     bottom=medium)
            else:
                cell.border = normal_cells_border

            cell.font = font_Arial9
            cell.alignment = center_alignment

    ## REFORMATAGE VALUE HEADER ##
    titres_columns = ['G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R']
    dict_titre_columns = {
        'G': 'Survie Male - 7 jours',
        'H': 'Alimentation',
        'I': 'Neurotoxicité AChE',
        'K': 'Survie Femelle',
        'L': 'Nombre jours exposition in situ',
        'M': 'n',
        'N': 'Fécondité',
        'O': 'n',
        'P': 'Cycle de mue',
        'Q': 'n',
        'R': 'Perturbation endocrinienne'
    }
    subtitle = ['L', 'N', 'P', 'R', 'G', 'H', 'I', 'K']
    n_merge = ['L3:L4', 'M3:M4', 'O3:O4', 'Q3:Q4']

    ws['N4'].value = "indice"
    ws['P4'].value = "valeur observée (valeur attendue)"
    ws['R4'].value = "surface ovocytaire moyenne (µm²)"

    # Nettoyage entre 2 tableaux
    cell = ws['J4']
    cell.border = Border(top=no_border, bottom=no_border)
    ws.column_dimensions['J'].width = 3

    # Merge et style des colonnes
    for merge_column in n_merge:
        ws.merge_cells(merge_column)
        top_left_cell = ws[merge_column[0:2]]
        top_left_cell.value = dict_titre_columns[merge_column[0]]
        top_left_cell.font = font_title
        top_left_cell.border = medium_border

    # Style des titres
    for column in titres_columns:
        if column in ['L', 'P', 'R']:
            ws.column_dimensions[column].width = 35
        elif column in ['M', 'O', 'Q']:
            ws.column_dimensions[column].width = 5
        else:
            ws.column_dimensions[column].width = 20

        cell = ws[column + "3"]
        cell.value = dict_titre_columns[column]
        cell.font = font_title
        cell.alignment = center_alignment
        cell.border = medium_border

    # Style des sous-titres
    for column in subtitle:
        cell = ws[column + "4"]
        cell.font = font_small_title
        cell.border = medium_border

    # Nettoyage des borders des données cachées

    ws["T4"].border = Border(top=no_border,
                             left=no_border,
                             right=no_border,
                             bottom=no_border)
    ws["u4"].border = Border(top=no_border,
                             left=no_border,
                             right=no_border,
                             bottom=no_border)

    ## STYLE VALUE DATA
    columns = [
        get_column_letter(col_idx) for col_idx in range(6, nb_columns + 2)
    ]
    little_border_columns = [
        'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R'
    ]
    na = ['L', 'M', 'N', 'O', 'P', 'Q', 'R']

    body_fill_ok = PatternFill(fill_type='solid',
                               start_color='027ee3',
                               end_color='027ee3')  #bleu
    body_fill_not_ok_1 = PatternFill(fill_type='solid',
                                     start_color='69a64b',
                                     end_color='69a64b')  #green
    body_fill_not_ok_2 = PatternFill(fill_type='solid',
                                     start_color='d1c452',
                                     end_color='d1c452')  #yellow
    body_fill_not_ok_3 = PatternFill(fill_type='solid',
                                     start_color='cc7931',
                                     end_color='cc7931')  #orange
    body_fill_not_ok_4 = PatternFill(fill_type='solid',
                                     start_color='ab2222',
                                     end_color='ab2222')  #red
    body_fill_NA = PatternFill(fill_type='solid',
                               start_color='abadb0',
                               end_color='abadb0')  # grey

    # la requete qui retourne les resultats des constantes r2 selon le paramétre
    threshold_data = QueryScript(
        f" SELECT parameter, threshold   FROM {env.DATABASE_TREATED}.r2_threshold WHERE threshold IS NOT NULL and version=  {env.CHOSEN_VERSION()}"
    ).execute()
    threshold_list = []
    for column in columns:

        threshold = None
        if column == 'H':
            threshold = []
            for element in threshold_data:
                if element[0] == 'alimentation':
                    threshold.append(element[1])
            threshold_list.append(threshold)
        if column == 'I':
            threshold = []
            for element in threshold_data:
                if element[0] == 'neurotoxicité AChE':
                    threshold.append(element[1])
            threshold_list.append(threshold)
        if column == 'N':
            threshold = []
            for element in threshold_data:
                if element[0] == 'reproduction':
                    threshold.append(element[1])
            threshold_list.append(threshold)
        if column == 'P':
            threshold = []
            for element in threshold_data:
                if element[0] == 'mue':
                    threshold.append(element[1])
        if column == 'R':
            threshold = []
            for element in threshold_data:
                if element[0] == 'perturbation endocrinienne':
                    threshold.append(element[1])

        if threshold:
            value = None
            for row in range(5, nb_rows + 5):
                cell = ws[column + str(row)]

                if isinstance(cell.value, float) or isinstance(
                        cell.value, int) or (isinstance(cell.value, str)
                                             and cell.value[:2] != "NA"):
                    value = -float(cell.value) if cell.value else None

                if cell.value != None:
                    already_done = False
                    if column == 'H':
                        survival_result = float(
                            ws['G' +
                               str(row)].value if ws['G' + str(row)].value
                            and ws['G' + str(row)].value != 'NA' else 0)
                        if survival_result != None and survival_result < 70:
                            if survival_result < 50:
                                already_done = True
                            else:
                                cell.fill = body_fill_NA
                                already_done = True

                    if not already_done:
                        if value and value >= threshold[0]:
                            if len(threshold) >= 1 and value >= threshold[1]:
                                if len(threshold
                                       ) >= 2 and value >= threshold[2]:
                                    if len(threshold
                                           ) >= 3 and value >= threshold[3]:
                                        cell.fill = body_fill_not_ok_4
                                    else:
                                        cell.fill = body_fill_not_ok_3
                                else:
                                    cell.fill = body_fill_not_ok_2
                            else:
                                cell.fill = body_fill_not_ok_1
                        else:
                            cell.fill = body_fill_ok

        if column == 'G' or column == 'H' or column == 'I' or column == 'K':
            cell = ws[column + "4"]
            cell.value = '%'

    # pour faire les bordures des colones et ligne selon les case et les centrer
    for column in little_border_columns:
        for row in range(5, 5 + nb_rows):
            ws[column + str(row)].border = normal_cells_border
            ws[column + str(row)].alignment = alignment_center

    # colorer les cycle de mue et la Perturbation endocrinienne
    for row in range(5, nb_rows + 5):

        mue = ws["T" + str(row)].value
        surface_retard = ws["U" + str(row)].value
        if ws["O" + str(row)].value:
            try:
                value = int(ws["O" + str(row)].value)
                if int(ws["O" + str(row)].value) >= 10:
                    if ws["R" + str(
                            row
                    )].value == "NA" or surface_retard == "Conforme BC1":
                        ws["R" + str(row)].fill = body_fill_ok
                    else:
                        ws["R" + str(row)].fill = body_fill_not_ok_4

                    if mue == "NA":
                        ws["P" + str(row)].fill = body_fill_NA
                    if mue == "Conforme":
                        ws["P" + str(row)].fill = body_fill_ok
                    if mue == "Retard modéré":
                        ws["P" + str(row)].fill = body_fill_NA
                    if mue == "Retard fort":
                        ws["P" + str(row)].fill = body_fill_not_ok_4
                else:
                    ws["R" + str(row)].fill = body_fill_NA
                    ws["P" + str(row)].fill = body_fill_NA
                    ws["N" + str(row)].fill = body_fill_NA
            except ValueError:
                ws["R" + str(row)].fill = body_fill_NA
                ws["P" + str(row)].fill = body_fill_NA
                ws["N" + str(row)].fill = body_fill_NA
        else:
            ws["R" + str(row)].fill = body_fill_NA
            ws["P" + str(row)].fill = body_fill_NA
            ws["N" + str(row)].fill = body_fill_NA

        ws["S" + str(row)].value = ""
        ws["T" + str(row)].value = ""
        ws["U" + str(row)].value = ""

    #si la survie femelle est egale à 0 ou bien il y'a pas donner la coloration de la ligne sera grise
    for row in range(5, nb_rows + 5):
        value = ws["K" + str(row)].value

        testNone = value is None
        testInt = isinstance(value, int) and float(value) == 0
        testStr = isinstance(value, str) and value[:4] == 'None'
        if testNone or testInt or testStr:
            for column in na:
                ws[column + str(row)].value = "NA"
                if column == "N" or column == "P" or column == "R":
                    ws[column + str(row)].fill = body_fill_NA
    ws.freeze_panes = ws["F8"]

    wb.save(PATH)
    wb.close()

    wb = load_workbook(PATH)
    ws = wb['Tox']
    ## Add threshold table
    ws.insert_rows(1)
    ws.insert_rows(1)
    ws.insert_rows(1)

    ws["F1"].value = "Effet faible"
    ws["F2"].value = "Effet modéré"
    ws["F3"].value = "Effet élevé"
    ws["F4"].value = "Effet très élevé"
    ws.column_dimensions['F'].width = 20
    header_columns = [
        get_column_letter(col_idx)
        for col_idx in list(range(2, nb_columns + 2))
    ]
    for letter in header_columns[5:]:
        index = None
        if letter == 'H':
            index = 0
        if letter == 'I':
            index = 1
        if letter == 'N':
            index = 2
        if index != None:
            [threshold, graduate_25, graduate_50,
             graduate_75] = threshold_list[index]
            ws[letter + "1"].value = -threshold
            ws[letter + "1"].border = medium_border
            ws[letter + "2"].value = -graduate_25
            ws[letter + "2"].border = medium_border
            ws[letter + "3"].value = -graduate_50
            ws[letter + "3"].border = medium_border
            ws[letter + "4"].value = -graduate_75
            ws[letter + "4"].border = medium_border

    ## REFORMATAGE STATIONS HEADER ##
    merging_cells = ['B5:B7', 'C5:C7', 'D5:D7', 'E5:E7']
    border_cells = ['B5', 'B7', 'C5', 'C7', 'D5', 'D7', 'E5', 'E7']

    merging_names = ['Campagne', 'Numéro', 'Station de mesure', 'Code Agence']

    # merger les cellules selon la taille de l'entete d'excel
    for i in range(len(merging_cells)):
        cells = merging_cells[i]
        top_left_cell = ws[cells[0:2]]
        name = merging_names[i]

        ws.merge_cells(cells)
        top_left_cell.value = name
        top_left_cell.font = header_stations_font
        top_left_cell.fill = header_stations_fill
        top_left_cell.alignment = center_alignment

    for cell in border_cells:
        ws[cell].border = medium_border

    wb.save(PATH)
    wb.close()
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 = 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
    # 12 is the starting line number of the last line chart in the report period

    ca_len = len(report['reporting_period']['names'])
    current_sheet_parameters_row_number = chart_start_row_number + ca_len * 6
    if 'parameters' not in report.keys() or \
            report['parameters'] is None or \
            'names' not in report['parameters'].keys() or \
            report['parameters']['names'] is None or \
            len(report['parameters']['names']) == 0 or \
            'timestamps' not in report['parameters'].keys() or \
            report['parameters']['timestamps'] is None or \
            len(report['parameters']['timestamps']) == 0 or \
            'values' not in report['parameters'].keys() or \
            report['parameters']['values'] is None or \
            len(report['parameters']['values']) == 0 or \
            timestamps_data_all_equal_0(report['parameters']['timestamps']):
        has_parameters_names_and_timestamps_and_values_data = False
    if has_parameters_names_and_timestamps_and_values_data:

        ###############################
        # new worksheet
        ###############################

        parameters_data = report['parameters']

        parameters_names_len = len(parameters_data['names'])

        parameters_ws = wb.create_sheet('相关参数')

        parameters_timestamps_data_max_len = \
            get_parameters_timestamps_lists_max_len(list(parameters_data['timestamps']))

        # Row height
        parameters_ws.row_dimensions[1].height = 102
        for i in range(2, 7 + 1):
            parameters_ws.row_dimensions[i].height = 42

        for i in range(8, parameters_timestamps_data_max_len + 10):
            parameters_ws.row_dimensions[i].height = 60

        # Col width
        parameters_ws.column_dimensions['A'].width = 1.5

        parameters_ws.column_dimensions['B'].width = 25.0

        for i in range(3, 12 + parameters_names_len * 3):
            parameters_ws.column_dimensions[format_cell.get_column_letter(
                i)].width = 15.0

        # Img
        img = Image("excelexporters/myems.png")
        img.width = img.width * 0.85
        img.height = img.height * 0.85
        # img = Image("myems.png")
        parameters_ws.add_image(img, 'B1')

        # Title
        parameters_ws.row_dimensions[3].height = 60

        parameters_ws['B3'].font = name_font
        parameters_ws['B3'].alignment = b_r_alignment
        parameters_ws['B3'] = 'Name:'
        parameters_ws['C3'].border = b_border
        parameters_ws['C3'].alignment = b_c_alignment
        parameters_ws['C3'].font = name_font
        parameters_ws['C3'] = name

        parameters_ws['D3'].font = name_font
        parameters_ws['D3'].alignment = b_r_alignment
        parameters_ws['D3'] = 'Period:'
        parameters_ws['E3'].border = b_border
        parameters_ws['E3'].alignment = b_c_alignment
        parameters_ws['E3'].font = name_font
        parameters_ws['E3'] = period_type

        parameters_ws['F3'].font = name_font
        parameters_ws['F3'].alignment = b_r_alignment
        parameters_ws['F3'] = 'Date:'
        parameters_ws['G3'].border = b_border
        parameters_ws['G3'].alignment = b_c_alignment
        parameters_ws['G3'].font = name_font
        parameters_ws[
            'G3'] = reporting_start_datetime_local + "__" + reporting_end_datetime_local
        parameters_ws.merge_cells("G3:H3")

        parameters_ws_current_row_number = 6

        parameters_ws['B' +
                      str(parameters_ws_current_row_number)].font = title_font
        parameters_ws['B' +
                      str(parameters_ws_current_row_number)] = name + ' 相关参数'

        parameters_ws_current_row_number += 1

        parameters_table_start_row_number = parameters_ws_current_row_number

        parameters_ws.row_dimensions[
            parameters_ws_current_row_number].height = 80

        parameters_ws_current_row_number += 1

        table_current_col_number = 2

        for i in range(0, parameters_names_len):

            if len(parameters_data['timestamps'][i]) == 0:
                continue

            col = format_cell.get_column_letter(table_current_col_number)

            parameters_ws[col + str(parameters_ws_current_row_number -
                                    1)].fill = table_fill
            parameters_ws[col + str(parameters_ws_current_row_number -
                                    1)].border = f_border

            col = format_cell.get_column_letter(table_current_col_number + 1)

            parameters_ws[col + str(parameters_ws_current_row_number -
                                    1)].fill = table_fill
            parameters_ws[col + str(parameters_ws_current_row_number -
                                    1)].border = f_border
            parameters_ws[col + str(parameters_ws_current_row_number -
                                    1)].font = name_font
            parameters_ws[col + str(parameters_ws_current_row_number -
                                    1)].alignment = c_c_alignment
            parameters_ws[col + str(parameters_ws_current_row_number -
                                    1)] = parameters_data['names'][i]

            table_current_row_number = parameters_ws_current_row_number

            for j, value in enumerate(list(parameters_data['timestamps'][i])):
                col = format_cell.get_column_letter(table_current_col_number)

                parameters_ws[col +
                              str(table_current_row_number)].border = f_border
                parameters_ws[col +
                              str(table_current_row_number)].font = title_font
                parameters_ws[
                    col +
                    str(table_current_row_number)].alignment = c_c_alignment
                parameters_ws[col + str(table_current_row_number)] = value

                col = format_cell.get_column_letter(table_current_col_number +
                                                    1)

                parameters_ws[col +
                              str(table_current_row_number)].border = f_border
                parameters_ws[col +
                              str(table_current_row_number)].font = title_font
                parameters_ws[
                    col +
                    str(table_current_row_number)].alignment = c_c_alignment
                parameters_ws[col + str(table_current_row_number)] = round(
                    parameters_data['values'][i][j], 2)

                table_current_row_number += 1

            table_current_col_number = table_current_col_number + 3

        ########################################################
        # parameters chart and parameters table
        ########################################################

        ws['B' + str(current_sheet_parameters_row_number)].font = title_font
        ws['B' + str(current_sheet_parameters_row_number)] = name + ' 相关参数'

        current_sheet_parameters_row_number += 1

        chart_start_row_number = current_sheet_parameters_row_number

        col_index = 0

        for i in range(0, parameters_names_len):

            if len(parameters_data['timestamps'][i]) == 0:
                continue

            line = LineChart()
            data_col = 3 + col_index * 3
            labels_col = 2 + col_index * 3
            col_index += 1
            line.title = '相关参数 - ' + \
                         parameters_ws.cell(row=parameters_table_start_row_number, column=data_col).value
            labels = Reference(parameters_ws,
                               min_col=labels_col,
                               min_row=parameters_table_start_row_number + 1,
                               max_row=(len(parameters_data['timestamps'][i]) +
                                        parameters_table_start_row_number))
            line_data = Reference(
                parameters_ws,
                min_col=data_col,
                min_row=parameters_table_start_row_number,
                max_row=(len(parameters_data['timestamps'][i]) +
                         parameters_table_start_row_number))
            line.add_data(line_data, titles_from_data=True)
            line.set_categories(labels)
            line_data = line.series[0]
            line_data.marker.symbol = "circle"
            line_data.smooth = True
            line.x_axis.crosses = 'min'
            line.height = 8.25
            line.width = 24
            line.dLbls = DataLabelList()
            line.dLbls.dLblPos = 't'
            line.dLbls.showVal = False
            line.dLbls.showPercent = False
            chart_col = 'B'
            chart_cell = chart_col + str(chart_start_row_number)
            chart_start_row_number += 6
            ws.add_chart(line, chart_cell)

        current_sheet_parameters_row_number = chart_start_row_number

        current_sheet_parameters_row_number += 1

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

    return filename
def generate_excel(report, name, reporting_start_datetime_local,
                   reporting_end_datetime_local, period_type):
    wb = Workbook()
    ws = wb.active

    # Row height
    ws.row_dimensions[1].height = 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")
    img.width = img.width * 0.85
    img.height = img.height * 0.85
    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)] = reporting_period_data['means'][i] \
                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)] = reporting_period_data['medians'][i] \
                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)] = reporting_period_data['minimums'][i] \
                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)] = reporting_period_data['maximums'][i] \
                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)] = reporting_period_data['stdevs'][i] \
                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)] = reporting_period_data['variances'][i] \
                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: 详细数据
    # analysis_end_row_number+1~ analysis_end_row_number+1+line_charts_row_number+: line
    # detailed_start_row_number~ : the detailed data table
    ########################################################
    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'])
        # the detailed title
        line_charts_row_number = 6 * ca_len + 1
        analysis_end_row_number = 9 + 2 * ca_len
        detailed_start_row_number = analysis_end_row_number + line_charts_row_number + real_timestamps_len * 7

        ws['B' + str(detailed_start_row_number)].font = title_font
        ws['B' + str(detailed_start_row_number)] = name + ' 详细数据'
        # the detailed 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
        # the detailed 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)] = values[index][i]
                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)] = reporting_period_data['subtotals'][i]
            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.height = 8.40  # cm 1.05*8 1.05cm = 30 pt
            line.width = 24
            line.x_axis.majorTickMark = 'in'
            line.y_axis.majorTickMark = 'in'
            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))

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

        has_associated_equipment_flag = True

        if "associated_equipment" not in report.keys() or \
                "energy_category_names" not in report['associated_equipment'].keys() or \
                len(report['associated_equipment']["energy_category_names"]) == 0 \
                or 'associated_equipment_names_array' not in report['associated_equipment'].keys() \
                or report['associated_equipment']['associated_equipment_names_array'] is None \
                or len(report['associated_equipment']['associated_equipment_names_array']) == 0 \
                or len(report['associated_equipment']['associated_equipment_names_array'][0]) == 0:
            has_associated_equipment_flag = False

        if has_associated_equipment_flag:
            associated_equipment = report['associated_equipment']

            current_row_number = detailed_start_row_number + 4 + time_len

            ws['B' + str(current_row_number)].font = title_font
            ws['B' + str(current_row_number)] = name + ' 相关设备数据'

            current_row_number += 1
            table_start_row_number = current_row_number

            ws.row_dimensions[current_row_number].height = 60
            ws['B' + str(current_row_number)].fill = table_fill
            ws['B' + str(current_row_number)].font = name_font
            ws['B' + str(current_row_number)].alignment = c_c_alignment
            ws['B' + str(current_row_number)].border = f_border
            ws['B' + str(current_row_number)] = '相关设备'
            ca_len = len(associated_equipment['energy_category_names'])

            for i in range(0, ca_len):
                row = chr(ord('C') + i)
                ws[row + str(current_row_number)].fill = table_fill
                ws[row + str(current_row_number)].font = name_font
                ws[row + str(current_row_number)].alignment = c_c_alignment
                ws[row + str(current_row_number)].border = f_border
                ws[row + str(current_row_number)] = \
                    reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"

            associated_equipment_len = len(
                associated_equipment['associated_equipment_names_array'][0])

            for i in range(0, associated_equipment_len):
                current_row_number += 1
                row = str(current_row_number)

                ws['B' + row].font = title_font
                ws['B' + row].alignment = c_c_alignment
                ws['B' + row] = associated_equipment[
                    'associated_equipment_names_array'][0][i]
                ws['B' + row].border = f_border

                for j in range(0, ca_len):
                    col = chr(ord('C') + j)
                    ws[col + row].font = title_font
                    ws[col + row].alignment = c_c_alignment
                    ws[col + row] = round(
                        associated_equipment['subtotals_array'][j][i], 2)
                    ws[col + row].border = f_border
    ####################################################################################################################
    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 generate_excel(report,
                   name,
                   reporting_start_datetime_local,
                   reporting_end_datetime_local,
                   period_type):
    wb = Workbook()
    ws = wb.active
    ws.title = "EquipmentLoad"

    # Row height
    ws.row_dimensions[1].height = 102

    for i in range(2, 2000 + 1):
        ws.row_dimensions[i].height = 42

    # Col width
    ws.column_dimensions['A'].width = 1.5
    ws.column_dimensions['B'].width = 25.0

    for i in range(ord('C'), ord('L')):
        ws.column_dimensions[chr(i)].width = 15.0

    # Font
    name_font = Font(name='Arial', size=15, bold=True)
    title_font = Font(name='Arial', size=15, bold=True)

    table_fill = PatternFill(fill_type='solid', fgColor='1F497D')
    f_border = Border(left=Side(border_style='medium', color='00000000'),
                      right=Side(border_style='medium', color='00000000'),
                      bottom=Side(border_style='medium', color='00000000'),
                      top=Side(border_style='medium', color='00000000')
                      )
    b_border = Border(bottom=Side(border_style='medium', color='00000000'), )

    b_c_alignment = Alignment(vertical='bottom',
                              horizontal='center',
                              text_rotation=0,
                              wrap_text=True,
                              shrink_to_fit=False,
                              indent=0)
    c_c_alignment = Alignment(vertical='center',
                              horizontal='center',
                              text_rotation=0,
                              wrap_text=True,
                              shrink_to_fit=False,
                              indent=0)
    b_r_alignment = Alignment(vertical='bottom',
                              horizontal='right',
                              text_rotation=0,
                              wrap_text=True,
                              shrink_to_fit=False,
                              indent=0)

    # Img
    img = Image("excelexporters/myems.png")
    ws.add_image(img, 'A1')

    # Title
    ws['B3'].alignment = b_r_alignment
    ws['B3'] = 'Name:'
    ws['C3'].border = b_border
    ws['C3'].alignment = b_c_alignment
    ws['C3'] = name

    ws['D3'].alignment = b_r_alignment
    ws['D3'] = 'Period:'
    ws['E3'].border = b_border
    ws['E3'].alignment = b_c_alignment
    ws['E3'] = period_type

    ws['B4'].alignment = b_r_alignment
    ws['B4'] = 'Reporting Start Datetime:'
    ws['C4'].border = b_border
    ws['C4'].alignment = b_c_alignment
    ws['C4'] = reporting_start_datetime_local

    ws['D4'].alignment = b_r_alignment
    ws['D4'] = 'Reporting End Datetime:'
    ws['E4'].border = b_border
    ws['E4'].alignment = b_c_alignment
    ws['E4'] = reporting_end_datetime_local

    if "reporting_period" not in report.keys() or \
            "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0:
        filename = str(uuid.uuid4()) + '.xlsx'
        wb.save(filename)

        return filename
    ####################################################################################################################
    # First: Statistics
    # 6: title
    # 7: table title
    # 8~2*ca_len table_data
    ####################################################################################################################
    reporting_period_data = report['reporting_period']

    if "names" not in reporting_period_data.keys() or \
            reporting_period_data['names'] is None or \
            len(reporting_period_data['names']) == 0:
        filename = str(uuid.uuid4()) + '.xlsx'
        wb.save(filename)
        return filename

    ws['B6'].font = title_font
    ws['B6'] = name + ' ' + 'Statistics'

    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'] = 'Reporting Period'
    ws['B7'].border = f_border

    ws['C7'].font = title_font
    ws['C7'].alignment = c_c_alignment
    ws['C7'] = 'Average Load'
    ws['C7'].border = f_border

    ws['D7'].font = title_font
    ws['D7'].alignment = c_c_alignment
    ws['D7'] = 'Maximum Load'
    ws['D7'].border = f_border

    ws['E7'].font = title_font
    ws['E7'].alignment = c_c_alignment
    ws['E7'] = 'Load Factor'
    ws['E7'].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] + "/H )"
        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)] = 'Increment Rate'
        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['averages'][i], 2) \
            if reporting_period_data['averages'][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['averages_increment_rate'][i] * 100, 2)) + "%" \
            if reporting_period_data['averages_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['maximums'][i], 2) \
            if reporting_period_data['maximums'][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['maximums_increment_rate'][i] * 100, 2)) + "%" \
            if reporting_period_data['maximums_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['factors'][i], 2) \
            if reporting_period_data['factors'][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['factors_increment_rate'][i] * 100, 2)) + "%" \
            if reporting_period_data['factors_increment_rate'][i] is not None else '0.00%'
        ws['E' + str(row + 1)].border = f_border

    ####################################################################################################################
    # Third: Detailed Data
    # row_sat~ row_sat + 6*cal_len: line
    # row_da: table title
    # row_da + 1~: 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]
        names = reporting_period_data['names']
        ca_len = len(names)
        real_timestamps_len = timestamps_data_not_equal_0(report['parameters']['timestamps'])
        time_len = len(timestamps)
        # row_lines == the number of rows of lines
        row_lines = 6 * ca_len
        # row_sat == the number of rows of statistical analysis table
        row_sat = 9 + 2 * ca_len
        # row_da == the number of rows of Detailed data
        row_da = row_sat + row_lines + real_timestamps_len * 7 + 2

        ws['B' + str(row_da)].font = title_font
        ws['B' + str(row_da)] = name + ' ' + 'Detailed Data'
        # table_title
        ws['B' + str(row_da + 1)].fill = table_fill
        ws['B' + str(row_da + 1)].font = name_font
        ws['B' + str(row_da + 1)].alignment = c_c_alignment
        ws['B' + str(row_da + 1)] = "Datetime"
        ws['B' + str(row_da + 1)].border = f_border

        for i in range(0, ca_len):
            col_average = chr(ord('C') + 2 * i)
            col_maximum = chr(ord('D') + 2 * i)

            ws[col_average + str(row_da + 1)].font = name_font
            ws[col_average + str(row_da + 1)].alignment = c_c_alignment
            ws[col_average + str(row_da + 1)] = names[i] + " Average Load(" + reporting_period_data['units'][
                i] + "/H)"
            ws[col_average + str(row_da + 1)].border = f_border

            ws[col_maximum + str(row_da + 1)].font = name_font
            ws[col_maximum + str(row_da + 1)].alignment = c_c_alignment
            ws[col_maximum + str(row_da + 1)] = names[i] + " Maximum Load(" + reporting_period_data['units'][
                i] + "/H)"
            ws[col_maximum + str(row_da + 1)].border = f_border
        # table_date
        for i in range(0, time_len):
            rows = i + row_da + 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_average = chr(ord('C') + 2 * index)
                col_maximum = chr(ord('D') + 2 * index)

                ws[col_average + str(rows)].font = name_font
                ws[col_average + str(rows)].alignment = c_c_alignment
                ws[col_average + str(rows)] = reporting_period_data['sub_averages'][index][i] \
                    if reporting_period_data['sub_maximums'][index] is not None else ''
                ws[col_average + str(rows)].number_format = '0.00'
                ws[col_average + str(rows)].border = f_border

                ws[col_maximum + str(rows)].font = name_font
                ws[col_maximum + str(rows)].alignment = c_c_alignment
                ws[col_maximum + str(rows)] = reporting_period_data['sub_maximums'][index][i] \
                    if reporting_period_data['sub_maximums'][index] is not None else ''
                ws[col_maximum + str(rows)].number_format = '0.00'
                ws[col_maximum + str(rows)].border = f_border
        current_row_number = row_da + 1 + time_len

        # LineChart
        for i in range(0, ca_len):
            lc = LineChart()
            lc.title = "Reporting Period Maximum Load"
            lc.style = 10
            lc.x_axis.majorTickMark = 'in'
            lc.y_axis.majorTickMark = 'in'
            lc.smooth = True
            lc.x_axis.crosses = 'min'
            lc.height = 8.25
            lc.width = 24
            lc.dLbls = DataLabelList()
            lc.dLbls.dLblPos = 't'
            lc.dLbls.showVal = True
            times = Reference(ws, min_col=2, min_row=row_da + 2,
                              max_row=row_da + 2 + time_len)
            lc_data = Reference(ws, min_col=2 + 2 * (i+1), min_row=row_da + 1,
                                max_row=row_da + 1 + time_len)
            lc.add_data(lc_data, titles_from_data=True)
            lc.set_categories(times)
            ser = lc.series[0]
            ser.marker.symbol = "diamond"
            ser.marker.size = 5
            chart_col = 'B'
            chart_cell = str(row_sat + 6 * i)
            ws.add_chart(lc, chart_col + chart_cell)

    ####################################################################################################################
    current_sheet_parameters_row_number = row_sat + 1 + 6 * ca_len
    has_parameters_names_and_timestamps_and_values_data = True
    if 'parameters' not in report.keys() or \
            report['parameters'] is None or \
            'names' not in report['parameters'].keys() or \
            report['parameters']['names'] is None or \
            len(report['parameters']['names']) == 0 or \
            'timestamps' not in report['parameters'].keys() or \
            report['parameters']['timestamps'] is None or \
            len(report['parameters']['timestamps']) == 0 or \
            'values' not in report['parameters'].keys() or \
            report['parameters']['values'] is None or \
            len(report['parameters']['values']) == 0 or \
            timestamps_data_all_equal_0(report['parameters']['timestamps']):
        has_parameters_names_and_timestamps_and_values_data = False
    if has_parameters_names_and_timestamps_and_values_data:

        ################################################################################################################
        # new worksheet
        ################################################################################################################

        parameters_data = report['parameters']
        parameters_names_len = len(parameters_data['names'])

        file_name = (re.sub(r'[^A-Z]', '', ws.title))+'_'
        parameters_ws = wb.create_sheet(file_name + 'Parameters')

        parameters_timestamps_data_max_len = \
            get_parameters_timestamps_lists_max_len(list(parameters_data['timestamps']))

        # Row height
        parameters_ws.row_dimensions[1].height = 102
        for i in range(2, 7 + 1):
            parameters_ws.row_dimensions[i].height = 42

        for i in range(8, parameters_timestamps_data_max_len + 10):
            parameters_ws.row_dimensions[i].height = 60

        # Col width
        parameters_ws.column_dimensions['A'].width = 1.5

        parameters_ws.column_dimensions['B'].width = 25.0

        for i in range(3, 12 + parameters_names_len * 3):
            parameters_ws.column_dimensions[format_cell.get_column_letter(i)].width = 15.0

        # Img
        img = Image("excelexporters/myems.png")
        parameters_ws.add_image(img, 'A1')

        # Title

        parameters_ws['B3'].alignment = b_r_alignment
        parameters_ws['B3'] = 'Name:'
        parameters_ws['C3'].border = b_border
        parameters_ws['C3'].alignment = b_c_alignment
        parameters_ws['C3'] = name

        parameters_ws['D3'].alignment = b_r_alignment
        parameters_ws['D3'] = 'Period:'
        parameters_ws['E3'].border = b_border
        parameters_ws['E3'].alignment = b_c_alignment
        parameters_ws['E3'] = period_type

        parameters_ws['B4'].alignment = b_r_alignment
        parameters_ws['B4'] = 'Reporting Start Datetime:'
        parameters_ws['C4'].border = b_border
        parameters_ws['C4'].alignment = b_c_alignment
        parameters_ws['C4'] = reporting_start_datetime_local

        parameters_ws['D4'].alignment = b_r_alignment
        parameters_ws['D4'] = 'Reporting End Datetime:'
        parameters_ws['E4'].border = b_border
        parameters_ws['E4'].alignment = b_c_alignment
        parameters_ws['E4'] = reporting_end_datetime_local

        parameters_ws_current_row_number = 6

        parameters_ws['B' + str(parameters_ws_current_row_number)].font = title_font
        parameters_ws['B' + str(parameters_ws_current_row_number)] = name + ' ' + 'Parameters'

        parameters_ws_current_row_number += 1

        parameters_table_start_row_number = parameters_ws_current_row_number

        parameters_ws.row_dimensions[parameters_ws_current_row_number].height = 80

        parameters_ws_current_row_number += 1

        table_current_col_number = 2

        for i in range(0, parameters_names_len):

            if len(parameters_data['timestamps'][i]) == 0:
                continue

            col = format_cell.get_column_letter(table_current_col_number)

            parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill
            parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border

            col = format_cell.get_column_letter(table_current_col_number + 1)

            parameters_ws[col + str(parameters_ws_current_row_number - 1)].fill = table_fill
            parameters_ws[col + str(parameters_ws_current_row_number - 1)].border = f_border
            parameters_ws[col + str(parameters_ws_current_row_number - 1)].font = name_font
            parameters_ws[col + str(parameters_ws_current_row_number - 1)].alignment = c_c_alignment
            parameters_ws[col + str(parameters_ws_current_row_number - 1)] = parameters_data['names'][i]

            table_current_row_number = parameters_ws_current_row_number

            for j, value in enumerate(list(parameters_data['timestamps'][i])):
                col = format_cell.get_column_letter(table_current_col_number)

                parameters_ws[col + str(table_current_row_number)].border = f_border
                parameters_ws[col + str(table_current_row_number)].font = title_font
                parameters_ws[col + str(table_current_row_number)].alignment = c_c_alignment
                parameters_ws[col + str(table_current_row_number)] = value

                col = format_cell.get_column_letter(table_current_col_number + 1)

                parameters_ws[col + str(table_current_row_number)].border = f_border
                parameters_ws[col + str(table_current_row_number)].font = title_font
                parameters_ws[col + str(table_current_row_number)].alignment = c_c_alignment
                parameters_ws[col + str(table_current_row_number)] = round(parameters_data['values'][i][j], 2)

                table_current_row_number += 1

            table_current_col_number = table_current_col_number + 3

        ################################################################################################################
        # parameters chart and parameters table
        ################################################################################################################

        ws['B' + str(current_sheet_parameters_row_number)].font = title_font
        ws['B' + str(current_sheet_parameters_row_number)] = name + ' ' + 'Parameters'

        current_sheet_parameters_row_number += 1

        chart_start_row_number = current_sheet_parameters_row_number

        col_index = 0

        for i in range(0, parameters_names_len):

            if len(parameters_data['timestamps'][i]) == 0:
                continue

            line = LineChart()
            data_col = 3 + col_index * 3
            labels_col = 2 + col_index * 3
            col_index += 1
            line.title = 'Parameters - ' + \
                         parameters_ws.cell(row=parameters_table_start_row_number, column=data_col).value
            labels = Reference(parameters_ws, min_col=labels_col, min_row=parameters_table_start_row_number + 1,
                               max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number))
            line_data = Reference(parameters_ws, min_col=data_col, min_row=parameters_table_start_row_number,
                                  max_row=(len(parameters_data['timestamps'][i]) + parameters_table_start_row_number))
            line.add_data(line_data, titles_from_data=True)
            line.set_categories(labels)
            line_data = line.series[0]
            line_data.marker.symbol = "circle"
            line_data.smooth = True
            line.x_axis.crosses = 'min'
            line.height = 8.25
            line.width = 24
            line.dLbls = DataLabelList()
            line.dLbls.dLblPos = 't'
            line.dLbls.showVal = False
            line.dLbls.showPercent = False
            chart_col = 'B'
            chart_cell = chart_col + str(chart_start_row_number)
            chart_start_row_number += 6
            ws.add_chart(line, chart_cell)

        current_sheet_parameters_row_number = chart_start_row_number

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

    return filename
Example #19
0
 def set_row_values(self, row, row_data_values):
     col=1
     for i in row_data_values:
         if i is not None:
             self.ws[get_column_letter(col)+str(row)]=i
         col+=1
Example #20
0
 def _to_reference(row, column):
     column_letter = get_column_letter(column)
     return column_letter + str(row)
Example #21
0
File: table.py Project: zhwycsz/edd
 def cell_coords(row_index, col_index):
     col_letter = get_column_letter(col_index + 1)
     return f"{col_letter}{row_index+1}"
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" not in report.keys() or \
            "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0:
        filename = str(uuid.uuid4()) + '.xlsx'
        wb.save(filename)

        return filename

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

    current_row_number = 6

    reporting_period_data = report['reporting_period']

    has_names_data_flag = True

    if "names" not in reporting_period_data.keys() or \
            reporting_period_data['names'] is None or \
            len(reporting_period_data['names']) == 0:
        has_names_data_flag = False

    if has_names_data_flag:
        ws['B' + str(current_row_number)].font = title_font
        ws['B' + str(current_row_number)] = name + ' 报告期消耗'

        current_row_number += 1

        category = reporting_period_data['names']
        ca_len = len(category)

        ws.row_dimensions[current_row_number].height = 60
        ws['B' + str(current_row_number)].fill = table_fill
        ws['B' + str(current_row_number)].border = f_border

        col = 'C'

        for i in range(0, ca_len):
            ws[col + str(current_row_number)].fill = table_fill
            ws[col + str(current_row_number)].font = name_font
            ws[col + str(current_row_number)].alignment = c_c_alignment
            ws[col + str(current_row_number)].border = f_border
            ws[col + str(current_row_number)] = \
                reporting_period_data['names'][i] + " " + reporting_period_data['energy_category_names'][i] + \
                " (" + reporting_period_data['units'][i] + ")"

            col = chr(ord(col) + 1)

        current_row_number += 1

        ws['B' + str(current_row_number)].font = title_font
        ws['B' + str(current_row_number)].alignment = c_c_alignment
        ws['B' + str(current_row_number)].border = f_border
        ws['B' + str(current_row_number)] = '消耗'

        col = 'C'

        for i in range(0, ca_len):
            ws[col + str(current_row_number)].font = name_font
            ws[col + str(current_row_number)].alignment = c_c_alignment
            ws[col + str(current_row_number)].border = f_border
            ws[col + str(current_row_number)] = round(
                reporting_period_data['subtotals'][i], 2)

            col = chr(ord(col) + 1)

        current_row_number += 1

        ws['B' + str(current_row_number)].font = title_font
        ws['B' + str(current_row_number)].alignment = c_c_alignment
        ws['B' + str(current_row_number)].border = f_border
        ws['B' + str(current_row_number)] = '单位面积值'

        col = 'C'

        for i in range(0, ca_len):
            ws[col + str(current_row_number)].font = name_font
            ws[col + str(current_row_number)].alignment = c_c_alignment
            ws[col + str(current_row_number)].border = f_border
            ws[col + str(current_row_number)] = round(
                reporting_period_data['subtotals_per_unit_area'][i], 2)

            col = chr(ord(col) + 1)

        current_row_number += 1

        ws['B' + str(current_row_number)].font = title_font
        ws['B' + str(current_row_number)].alignment = c_c_alignment
        ws['B' + str(current_row_number)].border = f_border
        ws['B' + str(current_row_number)] = '环比'

        col = 'C'

        for i in range(0, ca_len):
            ws[col + str(current_row_number)].font = name_font
            ws[col + str(current_row_number)].alignment = c_c_alignment
            ws[col + str(current_row_number)].border = f_border
            ws[col + str(current_row_number)] = str(
                round(reporting_period_data['increment_rates'][i] * 100, 2)) + '%' \
                if reporting_period_data['increment_rates'][i] is not None else '-'

            col = chr(ord(col) + 1)

        current_row_number += 2

        category_dict = group_by_category(
            reporting_period_data['energy_category_names'])

        for category_dict_name, category_dict_values in category_dict.items():

            ws['B' + str(current_row_number)].font = title_font
            ws['B' + str(current_row_number)] = \
                name + ' ' + category_dict_name + ' (' + reporting_period_data['units'][category_dict_values[0]] + \
                ') 分项消耗占比'

            current_row_number += 1
            table_start_row_number = current_row_number

            ws['B' + str(current_row_number)].fill = table_fill
            ws['B' + str(current_row_number)].border = f_border

            ws['C' + str(current_row_number)].font = name_font
            ws['C' + str(current_row_number)].fill = table_fill
            ws['C' + str(current_row_number)].alignment = c_c_alignment
            ws['C' + str(current_row_number)].border = f_border
            ws['C' + str(current_row_number)] = '消耗'

            current_row_number += 1

            for i in category_dict_values:
                ws['B' + str(current_row_number)].font = title_font
                ws['B' + str(current_row_number)].alignment = c_c_alignment
                ws['B' + str(current_row_number)].border = f_border
                ws['B' + str(current_row_number)] = \
                    reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
                ws['C' + str(current_row_number)].font = name_font
                ws['C' + str(current_row_number)].alignment = c_c_alignment
                ws['C' + str(current_row_number)].border = f_border
                ws['C' + str(current_row_number)] = round(
                    reporting_period_data['subtotals'][i], 3)

                current_row_number += 1

            table_end_row_number = current_row_number - 1

            pie = PieChart()
            pie.title = \
                name + ' ' + category_dict_name + ' (' + reporting_period_data['units'][category_dict_values[0]] + \
                ') 分项消耗占比'
            labels = Reference(ws,
                               min_col=2,
                               min_row=table_start_row_number + 1,
                               max_row=table_end_row_number)
            pie_data = Reference(ws,
                                 min_col=3,
                                 min_row=table_start_row_number,
                                 max_row=table_end_row_number)
            pie.add_data(pie_data, titles_from_data=True)
            pie.set_categories(labels)
            pie.height = 6.6
            pie.width = 9
            s1 = pie.series[0]
            s1.dLbls = DataLabelList()
            s1.dLbls.showCatName = False
            s1.dLbls.showVal = True
            s1.dLbls.showPercent = True
            ws.add_chart(pie, 'D' + str(table_start_row_number))

            if len(category_dict_values) < 4:
                current_row_number = current_row_number - len(
                    category_dict_values) + 4

            current_row_number += 1

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

    has_values_data = True
    has_timestamps_data = True

    if 'values' not in reporting_period_data.keys() or \
            reporting_period_data['values'] is None or \
            len(reporting_period_data['values']) == 0:
        has_values_data = False

    if 'timestamps' not in reporting_period_data.keys() or \
            reporting_period_data['timestamps'] is None or \
            len(reporting_period_data['timestamps']) == 0 or \
            len(reporting_period_data['timestamps'][0]) == 0:
        has_timestamps_data = False

    current_row_number += 1

    chart_start_row_number = current_row_number
    if has_values_data and has_timestamps_data:
        ca_len = len(reporting_period_data['names'])
        time = reporting_period_data['timestamps'][0]
        parameters_names_len = len(report['parameters']['names'])
        parameters_parameters_datas_len = 0

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

        for i in range(0, parameters_names_len):
            if len(report['parameters']['timestamps'][i]) == 0:
                continue
            parameters_parameters_datas_len += 1
        current_row_number = current_row_number + (
            ca_len + parameters_parameters_datas_len) * 6 + 2
        detail_data_table_start_row_number = current_row_number
        ws.row_dimensions[current_row_number].height = 60
        ws['B' + str(current_row_number)].fill = table_fill
        ws['B' + str(current_row_number)].font = title_font
        ws['B' + str(current_row_number)].alignment = c_c_alignment
        ws['B' + str(current_row_number)].border = f_border
        ws['B' + str(current_row_number)] = '日期时间'

        col = 'C'

        for i in range(0, ca_len):
            ws[col + str(current_row_number)].fill = table_fill
            ws[col + str(current_row_number)].font = title_font
            ws[col + str(current_row_number)].alignment = c_c_alignment
            ws[col + str(current_row_number)].border = f_border
            ws[col + str(current_row_number)] = \
                reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
            col = chr(ord(col) + 1)

        current_row_number += 1

        for i in range(0, len(time)):
            ws['B' + str(current_row_number)].font = title_font
            ws['B' + str(current_row_number)].alignment = c_c_alignment
            ws['B' + str(current_row_number)].border = f_border
            ws['B' + str(current_row_number)] = time[i]

            col = 'C'
            for j in range(0, ca_len):
                ws[col + str(current_row_number)].font = title_font
                ws[col + str(current_row_number)].alignment = c_c_alignment
                ws[col + str(current_row_number)].border = f_border
                ws[col + str(current_row_number)] = round(reporting_period_data['values'][j][i], 2) \
                    if reporting_period_data['values'][j][i] is not None else 0.00
                col = chr(ord(col) + 1)

            current_row_number += 1

        table_end_row_number = current_row_number - 1

        ws['B' + str(current_row_number)].font = title_font
        ws['B' + str(current_row_number)].alignment = c_c_alignment
        ws['B' + str(current_row_number)].border = f_border
        ws['B' + str(current_row_number)] = '小计'

        col = 'C'

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

        current_row_number += 2

        format_time_width_number = 1.0
        min_len_number = 1.0
        min_width_number = 11.0  # format_time_width_number * min_len_number + 4 and min_width_number > 11.0

        if period_type == 'hourly':
            format_time_width_number = 4.0
            min_len_number = 2
            min_width_number = 12.0
        elif period_type == 'daily':
            format_time_width_number = 2.5
            min_len_number = 4
            min_width_number = 14.0
        elif period_type == 'monthly':
            format_time_width_number = 2.1
            min_len_number = 4
            min_width_number = 12.4
        elif period_type == 'yearly':
            format_time_width_number = 1.5
            min_len_number = 5
            min_width_number = 11.5

        for i in range(0, ca_len):
            line = LineChart()
            line.title = '报告期消耗 - ' + \
                reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
            labels = Reference(ws,
                               min_col=2,
                               min_row=detail_data_table_start_row_number + 1,
                               max_row=table_end_row_number)
            line_data = Reference(ws,
                                  min_col=3 + i,
                                  min_row=detail_data_table_start_row_number,
                                  max_row=table_end_row_number)
            line.add_data(line_data, titles_from_data=True)
            line.set_categories(labels)
            line_data = line.series[0]
            line_data.marker.symbol = "circle"
            line_data.smooth = True
            line.x_axis.crosses = 'min'
            line.height = 8.25
            line.width = format_time_width_number * len(time) if len(
                time) > min_len_number else min_width_number
            if line.width > 24:
                line.width = 24
            line.dLbls = DataLabelList()
            line.dLbls.dLblPos = 't'
            line.dLbls.showVal = True
            line.dLbls.showPercent = False
            chart_col = 'B'
            chart_cell = chart_col + str(chart_start_row_number + 6 * i)
            ws.add_chart(line, chart_cell)

    ##########################################
    has_parameters_names_and_timestamps_and_values_data = True

    ca_len = len(report['reporting_period']['names'])
    current_sheet_parameters_row_number = chart_start_row_number + ca_len * 6
    if 'parameters' not in report.keys() or \
            report['parameters'] is None or \
            'names' not in report['parameters'].keys() or \
            report['parameters']['names'] is None or \
            len(report['parameters']['names']) == 0 or \
            'timestamps' not in report['parameters'].keys() or \
            report['parameters']['timestamps'] is None or \
            len(report['parameters']['timestamps']) == 0 or \
            'values' not in report['parameters'].keys() or \
            report['parameters']['values'] is None or \
            len(report['parameters']['values']) == 0 or \
            timestamps_data_all_equal_0(report['parameters']['timestamps']):
        has_parameters_names_and_timestamps_and_values_data = False
    if has_parameters_names_and_timestamps_and_values_data:

        ###############################
        # new worksheet
        ###############################

        parameters_data = report['parameters']

        parameters_names_len = len(parameters_data['names'])

        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 generate_excel(report, name, reporting_start_datetime_local,
                   reporting_end_datetime_local, period_type):

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

    # Row height
    ws.row_dimensions[1].height = 102

    for i in range(2, 2000 + 1):
        ws.row_dimensions[i].height = 42

    # Col width
    ws.column_dimensions['A'].width = 1.5

    ws.column_dimensions['B'].width = 25.0

    for i in range(ord('C'), ord('L')):
        ws.column_dimensions[chr(i)].width = 15.0

    # Font
    name_font = Font(name='Arial', size=15, bold=True)
    title_font = Font(name='Arial', size=15, bold=True)

    table_fill = PatternFill(fill_type='solid', fgColor='1F497D')
    f_border = Border(left=Side(border_style='medium', color='00000000'),
                      right=Side(border_style='medium', color='00000000'),
                      bottom=Side(border_style='medium', color='00000000'),
                      top=Side(border_style='medium', color='00000000'))
    b_border = Border(bottom=Side(border_style='medium', color='00000000'), )

    b_c_alignment = Alignment(vertical='bottom',
                              horizontal='center',
                              text_rotation=0,
                              wrap_text=True,
                              shrink_to_fit=False,
                              indent=0)
    c_c_alignment = Alignment(vertical='center',
                              horizontal='center',
                              text_rotation=0,
                              wrap_text=True,
                              shrink_to_fit=False,
                              indent=0)
    b_r_alignment = Alignment(vertical='bottom',
                              horizontal='right',
                              text_rotation=0,
                              wrap_text=True,
                              shrink_to_fit=False,
                              indent=0)

    # Img
    img = Image("excelexporters/myems.png")
    ws.add_image(img, 'A1')

    # Title
    ws['B3'].alignment = b_r_alignment
    ws['B3'] = 'Name:'
    ws['C3'].border = b_border
    ws['C3'].alignment = b_c_alignment
    ws['C3'] = name

    ws['D3'].alignment = b_r_alignment
    ws['D3'] = 'Period:'
    ws['E3'].border = b_border
    ws['E3'].alignment = b_c_alignment
    ws['E3'] = period_type

    ws['B4'].alignment = b_r_alignment
    ws['B4'] = 'Reporting Start Datetime:'
    ws['C4'].border = b_border
    ws['C4'].alignment = b_c_alignment
    ws['C4'] = reporting_start_datetime_local

    ws['D4'].alignment = b_r_alignment
    ws['D4'] = 'Reporting End Datetime:'
    ws['E4'].border = b_border
    ws['E4'].alignment = b_c_alignment
    ws['E4'] = reporting_end_datetime_local

    if "reporting_period" not in report.keys() or \
            "names" not in report['reporting_period'].keys() or len(report['reporting_period']['names']) == 0:
        filename = str(uuid.uuid4()) + '.xlsx'
        wb.save(filename)

        return filename
    ####################################################################################################################
    # First: Consumption
    # 6: title
    # 7: table title
    # 8~10 table_data
    # Total: 5 rows
    # if has not energy data: set low height for rows
    ####################################################################################################################
    reporting_period_data = report['reporting_period']

    has_energy_data_flag = True
    if "names" not in reporting_period_data.keys() or \
            reporting_period_data['names'] is None or \
            len(reporting_period_data['names']) == 0:
        has_energy_data_flag = False

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

        category = reporting_period_data['names']
        ca_len = len(category)

        ws.row_dimensions[7].height = 60
        ws['B7'].fill = table_fill
        ws['B7'].border = f_border

        ws['B8'].font = title_font
        ws['B8'].alignment = c_c_alignment
        ws['B8'] = 'Consumption'
        ws['B8'].border = f_border

        ws['B9'].font = title_font
        ws['B9'].alignment = c_c_alignment
        ws['B9'] = 'Per Unit Area'
        ws['B9'].border = f_border

        ws['B10'].font = title_font
        ws['B10'].alignment = c_c_alignment
        ws['B10'] = 'Increment Rate'
        ws['B10'].border = f_border

        col = ''

        for i in range(0, ca_len):
            col = chr(ord('C') + i)
            row = '7'
            cell = col + row
            ws[col + '7'].fill = table_fill
            ws[col + '7'].font = name_font
            ws[col + '7'].alignment = c_c_alignment
            ws[col + '7'] = reporting_period_data['names'][
                i] + " (" + reporting_period_data['units'][i] + ")"
            ws[col + '7'].border = f_border

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

            ws[col + '9'].font = name_font
            ws[col + '9'].alignment = c_c_alignment
            ws[col + '9'] = round(
                reporting_period_data['subtotals_per_unit_area'][i], 2)
            ws[col + '9'].border = f_border

            ws[col + '10'].font = name_font
            ws[col + '10'].alignment = c_c_alignment
            ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \
                if reporting_period_data['increment_rates'][i] is not None else "-"
            ws[col + '10'].border = f_border

        # TCE TCO2E
        end_col = col
        # TCE
        tce_col = chr(ord(end_col) + 1)
        ws[tce_col + '7'].fill = table_fill
        ws[tce_col + '7'].font = name_font
        ws[tce_col + '7'].alignment = c_c_alignment
        ws[tce_col + '7'] = 'Ton of Standard Coal (TCE)'
        ws[tce_col + '7'].border = f_border

        ws[tce_col + '8'].font = name_font
        ws[tce_col + '8'].alignment = c_c_alignment
        ws[tce_col + '8'] = round(
            reporting_period_data['total_in_kgce'] / 1000, 2)
        ws[tce_col + '8'].border = f_border

        ws[tce_col + '9'].font = name_font
        ws[tce_col + '9'].alignment = c_c_alignment
        ws[tce_col + '9'] = round(
            reporting_period_data['total_in_kgce_per_unit_area'] / 1000, 2)
        ws[tce_col + '9'].border = f_border

        ws[tce_col + '10'].font = name_font
        ws[tce_col + '10'].alignment = c_c_alignment
        ws[tce_col + '10'] = str(round(reporting_period_data['increment_rate_in_kgce'] * 100, 2)) + "%" \
            if reporting_period_data['increment_rate_in_kgce'] is not None else "-"
        ws[tce_col + '10'].border = f_border

        # TCO2E
        tco2e_col = chr(ord(end_col) + 2)
        ws[tco2e_col + '7'].fill = table_fill
        ws[tco2e_col + '7'].font = name_font
        ws[tco2e_col + '7'].alignment = c_c_alignment
        ws[tco2e_col + '7'] = 'Ton of Carbon Dioxide Emissions (TCO2E)'
        ws[tco2e_col + '7'].border = f_border

        ws[tco2e_col + '8'].font = name_font
        ws[tco2e_col + '8'].alignment = c_c_alignment
        ws[tco2e_col + '8'] = round(
            reporting_period_data['total_in_kgco2e'] / 1000, 2)
        ws[tco2e_col + '8'].border = f_border

        ws[tco2e_col + '9'].font = name_font
        ws[tco2e_col + '9'].alignment = c_c_alignment
        ws[tco2e_col + '9'] = round(
            reporting_period_data['total_in_kgco2e_per_unit_area'] / 1000, 2)
        ws[tco2e_col + '9'].border = f_border

        ws[tco2e_col + '10'].font = name_font
        ws[tco2e_col + '10'].alignment = c_c_alignment
        ws[tco2e_col + '10'] = str(round(reporting_period_data['increment_rate_in_kgco2e'] * 100, 2)) + "%" \
            if reporting_period_data['increment_rate_in_kgco2e'] is not None else "-"
        ws[tco2e_col + '10'].border = f_border
    else:
        for i in range(6, 10 + 1):
            ws.row_dimensions[i].height = 0.1
    ####################################################################################################################
    # Second: Electricity Consumption by Time-Of-Use
    # 12: title
    # 13: table title
    # 14~17 table_data
    # Total: 6 rows
    ####################################################################################################################
    has_ele_peak_flag = True
    if "toppeaks" not in reporting_period_data.keys() or \
            reporting_period_data['toppeaks'] is None or \
            len(reporting_period_data['toppeaks']) == 0:
        has_ele_peak_flag = False

    if has_ele_peak_flag:
        ws['B12'].font = title_font
        ws['B12'] = name + ' ' + 'Electricity Consumption by Time-Of-Use'

        ws.row_dimensions[13].height = 60
        ws['B13'].fill = table_fill
        ws['B13'].font = name_font
        ws['B13'].alignment = c_c_alignment
        ws['B13'].border = f_border

        ws['C13'].fill = table_fill
        ws['C13'].font = name_font
        ws['C13'].alignment = c_c_alignment
        ws['C13'].border = f_border
        ws['C13'] = 'Electricity Consumption by Time-Of-Use'

        ws['B14'].font = title_font
        ws['B14'].alignment = c_c_alignment
        ws['B14'] = 'TopPeak'
        ws['B14'].border = f_border

        ws['C14'].font = title_font
        ws['C14'].alignment = c_c_alignment
        ws['C14'].border = f_border
        ws['C14'] = round(reporting_period_data['toppeaks'][0], 2)

        ws['B15'].font = title_font
        ws['B15'].alignment = c_c_alignment
        ws['B15'] = 'OnPeak'
        ws['B15'].border = f_border

        ws['C15'].font = title_font
        ws['C15'].alignment = c_c_alignment
        ws['C15'].border = f_border
        ws['C15'] = round(reporting_period_data['onpeaks'][0], 2)

        ws['B16'].font = title_font
        ws['B16'].alignment = c_c_alignment
        ws['B16'] = 'MidPeak'
        ws['B16'].border = f_border

        ws['C16'].font = title_font
        ws['C16'].alignment = c_c_alignment
        ws['C16'].border = f_border
        ws['C16'] = round(reporting_period_data['midpeaks'][0], 2)

        ws['B17'].font = title_font
        ws['B17'].alignment = c_c_alignment
        ws['B17'] = 'OffPeak'
        ws['B17'].border = f_border

        ws['C17'].font = title_font
        ws['C17'].alignment = c_c_alignment
        ws['C17'].border = f_border
        ws['C17'] = round(reporting_period_data['offpeaks'][0], 2)

        pie = PieChart()
        pie.title = name + ' ' + 'Electricity Consumption by Time-Of-Use'
        labels = Reference(ws, min_col=2, min_row=14, max_row=17)
        pie_data = Reference(ws, min_col=3, min_row=13, max_row=17)
        pie.add_data(pie_data, titles_from_data=True)
        pie.set_categories(labels)
        pie.height = 7.25
        pie.width = 9
        s1 = pie.series[0]
        s1.dLbls = DataLabelList()
        s1.dLbls.showCatName = False  # 标签显示
        s1.dLbls.showVal = True  # 数量显示
        s1.dLbls.showPercent = True  # 百分比显示

        ws.add_chart(pie, "D13")

    else:
        for i in range(12, 18 + 1):
            ws.row_dimensions[i].height = 0.1

    ####################################################################################################################
    # Third: Ton of Standard Coal(TCE) by Energy Category
    # current_row_number: title
    # current_row_number + 1: table title
    # current_row_number + 1 + ca_len table_data
    # Total: 2 + ca_len rows
    ####################################################################################################################
    current_row_number = 19
    has_kgce_data_flag = True

    if "subtotals_in_kgce" not in reporting_period_data.keys() or \
            reporting_period_data['subtotals_in_kgce'] is None or \
            len(reporting_period_data['subtotals_in_kgce']) == 0:
        has_kgce_data_flag = False

    if has_kgce_data_flag:
        ws['B' + str(current_row_number)].font = title_font
        ws['B' +
           str(current_row_number
               )] = name + ' ' + 'Ton of Standard Coal(TCE) by Energy Category'

        current_row_number += 1
        table_start_row_number = current_row_number

        ws.row_dimensions[current_row_number].height = 60
        ws['B' + str(current_row_number)].fill = table_fill
        ws['B' + str(current_row_number)].font = name_font
        ws['B' + str(current_row_number)].alignment = c_c_alignment
        ws['B' + str(current_row_number)].border = f_border

        ws['C' + str(current_row_number)].fill = table_fill
        ws['C' + str(current_row_number)].font = name_font
        ws['C' + str(current_row_number)].alignment = c_c_alignment
        ws['C' + str(current_row_number)].border = f_border
        ws['C' + str(current_row_number
                     )] = 'Ton of Standard Coal(TCE) by Energy Category'

        current_row_number += 1

        ca_len = len(reporting_period_data['names'])

        for i in range(0, ca_len):
            ws['B' + str(current_row_number)].font = title_font
            ws['B' + str(current_row_number)].alignment = c_c_alignment
            ws['B' +
               str(current_row_number)] = reporting_period_data['names'][i]
            ws['B' + str(current_row_number)].border = f_border

            ws['C' + str(current_row_number)].font = title_font
            ws['C' + str(current_row_number)].alignment = c_c_alignment
            ws['C' + str(current_row_number)].border = f_border
            ws['C' + str(current_row_number)] = round(
                reporting_period_data['subtotals_in_kgce'][i] / 1000, 3)

            current_row_number += 1

        table_end_row_number = current_row_number - 1

        pie = PieChart()
        pie.title = name + ' ' + ws.cell(column=3,
                                         row=table_start_row_number).value
        labels = Reference(ws,
                           min_col=2,
                           min_row=table_start_row_number + 1,
                           max_row=table_end_row_number)
        pie_data = Reference(ws,
                             min_col=3,
                             min_row=table_start_row_number,
                             max_row=table_end_row_number)
        pie.add_data(pie_data, titles_from_data=True)
        pie.set_categories(labels)
        pie.height = 7.25
        pie.width = 9
        s1 = pie.series[0]
        s1.dLbls = DataLabelList()
        s1.dLbls.showCatName = False
        s1.dLbls.showVal = True
        s1.dLbls.showPercent = True
        table_cell = 'D' + str(table_start_row_number)
        ws.add_chart(pie, table_cell)

        if ca_len < 4:
            current_row_number = current_row_number - ca_len + 4

        current_row_number += 1
    ####################################################################################################################
    # Fourth: Ton of Carbon Dioxide Emissions(TCO2E) by Energy Category
    # current_row_number: title
    # current_row_number + 1: table title
    # current_row_number + 1 + ca_len table_data
    # Total: 2 + ca_len rows
    ####################################################################################################################
    has_kgco2e_data_flag = True

    if "subtotals_in_kgco2e" not in reporting_period_data.keys() or \
            reporting_period_data['subtotals_in_kgco2e'] is None or \
            len(reporting_period_data['subtotals_in_kgco2e']) == 0:
        has_kgco2e_data_flag = False

    if has_kgco2e_data_flag:
        ws['B' + str(current_row_number)].font = title_font
        ws['B' + str(
            current_row_number
        )] = name + ' ' + 'Ton of Carbon Dioxide Emissions(TCO2E) by Energy Category'

        current_row_number += 1
        table_start_row_number = current_row_number

        ws.row_dimensions[current_row_number].height = 75
        ws['B' + str(current_row_number)].fill = table_fill
        ws['B' + str(current_row_number)].font = name_font
        ws['B' + str(current_row_number)].alignment = c_c_alignment
        ws['B' + str(current_row_number)].border = f_border

        ws['C' + str(current_row_number)].fill = table_fill
        ws['C' + str(current_row_number)].font = name_font
        ws['C' + str(current_row_number)].alignment = c_c_alignment
        ws['C' + str(current_row_number)].border = f_border
        ws['C' +
           str(current_row_number
               )] = 'Ton of Carbon Dioxide Emissions(TCO2E) by Energy Category'

        current_row_number += 1

        ca_len = len(reporting_period_data['names'])

        for i in range(0, ca_len):
            ws['B' + str(current_row_number)].font = title_font
            ws['B' + str(current_row_number)].alignment = c_c_alignment
            ws['B' +
               str(current_row_number)] = reporting_period_data['names'][i]
            ws['B' + str(current_row_number)].border = f_border

            ws['C' + str(current_row_number)].font = title_font
            ws['C' + str(current_row_number)].alignment = c_c_alignment
            ws['C' + str(current_row_number)].border = f_border
            ws['C' + str(current_row_number)] = round(
                reporting_period_data['subtotals_in_kgco2e'][i] / 1000, 3)
            current_row_number += 1

        table_end_row_number = current_row_number - 1

        pie = PieChart()
        pie.title = name + ' ' + ws.cell(column=3,
                                         row=table_start_row_number).value
        labels = Reference(ws,
                           min_col=2,
                           min_row=table_start_row_number + 1,
                           max_row=table_end_row_number)
        pie_data = Reference(ws,
                             min_col=3,
                             min_row=table_start_row_number,
                             max_row=table_end_row_number)
        pie.add_data(pie_data, titles_from_data=True)
        pie.set_categories(labels)
        pie.height = 7.75
        pie.width = 9
        s1 = pie.series[0]
        s1.dLbls = DataLabelList()
        s1.dLbls.showCatName = False
        s1.dLbls.showVal = True
        s1.dLbls.showPercent = True
        table_cell = 'D' + str(table_start_row_number)
        ws.add_chart(pie, table_cell)

        if ca_len < 4:
            current_row_number = current_row_number - ca_len + 4

        current_row_number += 1

    ####################################################################################################################
    # Fifth: Detailed Data
    # current_row_number: title
    # current_row_number+1 ~ current_row_number+1+ca_len*6-1: line
    # current_row_number+1+ca_len*6: table title
    # current_row_number+1+ca_len*6~: table_data
    ####################################################################################################################
    reporting_period_data = report['reporting_period']
    times = reporting_period_data['timestamps']
    has_detail_data_flag = True
    ca_len = len(report['reporting_period']['names'])
    parameters_names_len = len(report['parameters']['names'])
    parameters_parameters_datas_len = 0
    for i in range(0, parameters_names_len):
        if len(report['parameters']['timestamps'][i]) == 0:
            continue
        parameters_parameters_datas_len += 1
    table_row = current_row_number + (ca_len +
                                      parameters_parameters_datas_len) * 6 + 2
    chart_start_row_number = current_row_number + 1
    if "timestamps" not in reporting_period_data.keys() or \
            reporting_period_data['timestamps'] is None or \
            len(reporting_period_data['timestamps']) == 0:
        has_detail_data_flag = False

    if has_detail_data_flag:
        ws['B' + str(current_row_number)].font = title_font
        ws['B' + str(current_row_number)] = name + ' ' + 'Detailed Data'

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

        if has_data:
            for i in range(0, len(time)):
                col = 'B'
                row = str(table_row + 1 + i)
                ws[col + row].font = title_font
                ws[col + row].alignment = c_c_alignment
                ws[col + row] = time[i]
                ws[col + row].border = f_border

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

                ws[col + str(table_row)].fill = table_fill
                ws[col + str(table_row)].font = title_font
                ws[col + str(table_row)].alignment = c_c_alignment
                ws[col + str(table_row)] = reporting_period_data['names'][i] + \
                    " (" + reporting_period_data['units'][i] + ")"
                ws[col + str(table_row)].border = f_border

                # 39 data
                time = times[i]
                time_len = len(time)

                for j in range(0, time_len):
                    row = str(table_row + 1 + j)
                    ws[col + row].font = title_font
                    ws[col + row].alignment = c_c_alignment
                    ws[col + row] = round(
                        reporting_period_data['values'][i][j], 2)
                    ws[col + row].border = f_border

            current_row_number = table_row + 1 + len(times[0])

            ws['B' + str(current_row_number)].font = title_font
            ws['B' + str(current_row_number)].alignment = c_c_alignment
            ws['B' + str(current_row_number)].border = f_border
            ws['B' + str(current_row_number)] = 'Subtotal'

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

                # line
                # 39~: line
                line = LineChart()
                line.title = 'Reporting Period Consumption - ' + ws.cell(
                    column=3 + i, row=table_row).value
                labels = Reference(ws,
                                   min_col=2,
                                   min_row=table_row + 1,
                                   max_row=max_row)
                line_data = Reference(ws,
                                      min_col=3 + i,
                                      min_row=table_row,
                                      max_row=max_row)  # openpyxl bug
                line.add_data(line_data, titles_from_data=True)
                line.set_categories(labels)
                line_data = line.series[0]
                line_data.marker.symbol = "circle"
                line_data.smooth = True
                line.x_axis.crosses = 'min'
                line.height = 8.25
                line.width = 24
                line.dLbls = DataLabelList()
                line.dLbls.dLblPos = 't'
                line.dLbls.showVal = True  # val show
                line.dLbls.showPercent = True  # percent show
                chart_col = 'B'
                chart_cell = chart_col + str(chart_start_row_number + 6 * i)
                ws.add_chart(line, chart_cell)

    ####################################################################################################################
    has_parameters_names_and_timestamps_and_values_data = True

    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 #24
0
def read_input_table(wb,excel_index):
    #Read in the top value in the sheet
    input_table_sheet = excel_index['Input table sheet']
    #Set worksheet to the input table sheet
    ws_input = wb['Input Table']
    input_table_offset = excel_index['Input table offset']
    total_towers = excel_index['Total number of towers']
    cur_tower_row = 1
    table_start_row = cur_tower_row + input_table_offset
    all_towers = []
    cur_tower_num = 1
    while cur_tower_num <= total_towers:
        #create tower object
        cur_tower = Tower(0,0,0,0,0,0,0,0,0,0,0)
        #read member material
        member_mat = ws_input['B'+str(cur_tower_row + 1)].value
        cur_tower.member_mat = member_mat
        #read rod material
        rod_mat = ws_input['B'+str(cur_tower_row + 2)].value
        cur_tower.rod_mat = rod_mat
        #read building footprint in square inches
        footprint = ws_input['B'+str(cur_tower_row + 3)].value
        cur_tower.footprint = footprint
        #read floor plans
        floor_pln_col = excel_index['Floor plan col']
        cur_floor_row = cur_tower_row + input_table_offset
        floor_plans = []
        while ws_input[floor_pln_col + str(cur_floor_row)].value is not None:
            floor_pln = ws_input[floor_pln_col + str(cur_floor_row)].value
            floor_plans.append(floor_pln)
            cur_floor_row = cur_floor_row + 1
        cur_tower.floor_plans = floor_plans
        #read floor heights
        floor_heights_col = excel_index['Floor height col']
        cur_floor_row = cur_tower_row + input_table_offset
        floor_heights = []
        while ws_input[floor_heights_col + str(cur_floor_row)].value is not None:
            floor_height = ws_input[floor_heights_col + str(cur_floor_row)].value
            floor_heights.append(floor_height)
            cur_floor_row = cur_floor_row + 1
        cur_tower.floor_heights = floor_heights
        #read column properties
        col_props_start_col = excel_index['Column properties start']
        col_props_end_col = excel_index['Column properties end']
        cur_floor_row = cur_tower_row + input_table_offset
        cur_col = col_props_start_col
        col_props = {}
        face = 1
        while ws_input[cur_col + str(cur_floor_row)].value is not None:
            col_props[face] = []
            while cur_col != get_column_letter(column_index_from_string(col_props_end_col)+1):
                col_prop = ws_input[cur_col + str(cur_floor_row)].value
                col_props[face] = col_prop
                cur_col = get_column_letter(column_index_from_string(cur_col)+1)
            cur_col = col_props_start_col
            cur_floor_row = cur_floor_row + 1
        cur_tower.col_props = col_props
        #read bracing properties
        bracing_types_start_col = excel_index['Bracing type start']
        bracing_types_end_col= excel_index['Bracing type end']
        cur_floor_row = cur_tower_row + input_table_offset
        cur_col = bracing_types_start_col
        bracing_types = {}
        face = 1
        while ws_input[cur_col + str(cur_floor_row)].value is not None:
            bracing_types[face] = []
            while cur_col != get_column_letter(column_index_from_string(bracing_types_end_col)+1):
                bracing_type = ws_input[cur_col + str(cur_floor_row)].value
                bracing_types[face].append(bracing_type)
                cur_col = get_column_letter(column_index_from_string(cur_col)+1)
            cur_col = bracing_types_start_col
            cur_floor_row = cur_floor_row + 1
            face += 1
        cur_tower.bracing_types = bracing_types
        #read floor masses
        floor_masses_col = excel_index['Floor mass col']
        cur_floor_row = cur_tower_row + input_table_offset
        floor_masses = []
        while ws_input[floor_masses_col + str(cur_floor_row)].value is not None:
            floor_mass = ws_input[floor_masses_col + str(cur_floor_row)].value
            floor_masses.append(floor_mass)
            cur_floor_row = cur_floor_row + 1
        cur_tower.floor_masses = floor_masses
        #read floor bracing types
        floor_bracing_col = excel_index['Floor bracing col']
        cur_floor_row = cur_tower_row + input_table_offset
        floor_bracing_types = []
        while ws_input[floor_bracing_col + str(cur_floor_row)].value is not None:
            floor_bracing = ws_input[floor_bracing_col + str(cur_floor_row)].value
            floor_bracing_types.append(floor_bracing)
            cur_floor_row = cur_floor_row + 1
        cur_tower.floor_bracing_types = floor_bracing_types
        #read number of sides
        side = []
        side_start_col = excel_index['Bracing type start']
        side_end_col= excel_index['Bracing type end']
        cur_side_row = cur_tower_row + input_table_offset - 1
        cur_col = side_start_col
        while cur_col != get_column_letter(column_index_from_string(side_end_col)+1):
            side_num = ws_input[cur_col + str(cur_side_row)].value
            side.append(side_num)
            cur_col = get_column_letter(column_index_from_string(cur_col)+1)
        cur_tower.side = side
        #increment
        cur_tower.number = cur_tower_num
        all_towers.append(cur_tower)
        cur_tower_num = cur_tower_num + 1
        cur_tower_row = cur_floor_row + 1
    return all_towers
Example #25
0
 def set_sheet_column_widths(self, sheet, widths):
     for index, width in enumerate(widths):
         sheet.column_dimensions[get_column_letter(index +
                                                   1)].width = widths[index]
Example #26
0
def add_auto_filters(sheet, start_column, start_row, length):
    start_column_idx = column_index_from_string(start_column)
    end_column  = get_column_letter(start_column_idx + length - 1)
    filter_range = start_column + str(start_row) +  ':' + end_column + str(start_row)
    sheet.auto_filter.ref = filter_range
Example #27
0
def mod_radfrac(worksheet, large_arr):
    rad_arr = []
    tempChangeFlag = 0
    temp_row = find_row_with_key(worksheet, "Calculated temperature [C]")
    if (temp_row == 0):
        tempChangeFlag = 1
        temp_row = find_row_with_key(worksheet, "Calculated temperature [K]")

    for arr in large_arr:
        current_block_name = (worksheet[(get_column_letter(arr[0] - 1) +
                                         "2")].value)
        if (current_block_name == "RadFrac"):
            rad_arr = arr

    for col in worksheet.iter_cols(min_col=rad_arr[0] - 1,
                                   max_col=rad_arr[0] - 1,
                                   min_row=111,
                                   max_row=111):
        for cell in col:
            cell.value = "Heat In, MW"
            cell.fill = GREEN_HIGHLIGHT

    for col in worksheet.iter_cols(min_col=rad_arr[0] - 1,
                                   max_col=rad_arr[0] - 1,
                                   min_row=112,
                                   max_row=112):
        for cell in col:
            cell.value = "Heat Out, MW"
            cell.fill = GREEN_HIGHLIGHT

    for col in worksheet.iter_cols(min_col=rad_arr[0],
                                   max_col=rad_arr[len(rad_arr) - 1],
                                   min_row=33,
                                   max_row=33):  #Reboiler heat
        for cell in col:
            temp = cell.value
            cell.offset(row=111 - 33).value = temp

    for col in worksheet.iter_cols(min_col=rad_arr[0],
                                   max_col=rad_arr[len(rad_arr) - 1],
                                   min_row=27,
                                   max_row=27):  #Condensor heat duty
        for cell in col:
            temp = cell.value
            cell.offset(row=112 - 27).value = temp

    for col in worksheet.iter_cols(min_col=rad_arr[0],
                                   max_col=rad_arr[len(rad_arr) - 1],
                                   min_row=110,
                                   max_row=110):
        for cell in col:
            val1_off = cell.offset(row=32 - 110).value + 273.15
            val1 = cell.offset(row=1).value / val1_off
            val2_off = cell.offset(row=25 - 110).value + 273.15
            val2 = cell.offset(row=2).value / val2_off
            temp = cell.value - (val1 + val2) * 1000
            cell.value = temp

    for col in worksheet.iter_cols(min_col=rad_arr[0],
                                   max_col=rad_arr[len(rad_arr) - 1],
                                   min_row=temp_row,
                                   max_row=temp_row):
        for cell in col:
            print(cell.value)
Example #28
0
def generate_excel(report, name, reporting_start_datetime_local,
                   reporting_end_datetime_local, period_type):
    wb = Workbook()

    # todo
    ws = wb.active
    ws.title = "TenantLoad"
    # 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 \
            "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 + 'Reporting Period Average Load'

        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)] = 'Average Load'

        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)] = 'Per Unit Area'

        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)] = 'Increment Rate'

        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 + 'Reporting Period Maximum Load'

        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)] = 'Maximum Load'

        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)] = 'Per Unit Area'

        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)] = 'Increment Rate'

        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 + 'Reporting Period Load Factor'

        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)] = 'Load Factor'

        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)] = 'Increment Rate'

        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 + 'Detailed Data'

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

        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] + \
                    " Average Load(" + 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] + \
                    " Maximum Load(" + 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 = 'Reporting Period Average Load - ' + 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 = 'Reporting Period Maximum Load - ' + 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'])

        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 #29
0
def step_fourteen(worksheet):
    mass_balance_row = find_row_with_key(worksheet, "Mass balance kg/hr")
    block_arr = get_block_arr(worksheet)
    spec_arr = []
    large_arr = []
    sumVal = 0
    for block_range in block_arr:
        for x in range(block_range[0], block_range[1] + 1):
            spec_arr.append(x)
        large_arr.append(spec_arr)
        spec_arr = []

    for arr in large_arr:
        current_block_name = (worksheet[(get_column_letter(arr[0] - 1) +
                                         "2")].value)
        for col in arr:
            sumVal = float(0.0)
            curr = worksheet[(get_column_letter(col) + "67")].value  #Inlet1
            if (curr != None):
                sumVal += float(curr)
            curr = worksheet[(get_column_letter(col) + "71")].value  #Inlet2
            if (curr != None):
                sumVal += float(curr)
            curr = worksheet[(get_column_letter(col) + "75")].value  #Inlet3
            if (curr != None):
                sumVal += float(curr)
            curr = worksheet[(get_column_letter(col) + "79")].value  #Inlet4
            if (curr != None):
                sumVal += float(curr)
            curr = worksheet[(get_column_letter(col) + "83")].value  #Outlet1
            if (curr != None):
                sumVal -= float(curr)
            curr = worksheet[(get_column_letter(col) + "87")].value  #Outlet2
            if (curr != None):
                sumVal -= float(curr)
            curr = worksheet[(get_column_letter(col) + "91")].value  #Outlet3
            if (curr != None):
                sumVal -= float(curr)
            curr = worksheet[(get_column_letter(col) + "95")].value  #Outlet4
            if (curr != None):
                sumVal -= float(curr)
            curr = worksheet[(get_column_letter(col) + "99")].value  #Outlet5
            if (curr != None):
                sumVal -= float(curr)
            curr = worksheet[(get_column_letter(col) + "103")].value  #Outlet6
            if (curr != None):
                sumVal -= float(curr)
            writeCell = worksheet[(get_column_letter(col) + "108")]
            if (abs(sumVal <= 10)):
                writeCell.value = round_val(
                    sumVal)  #Write Cell - i.e Mass Balance
            else:
                writeCell.value = round_val(
                    sumVal)  #Write Cell - i.e Mass Balance
                print("MB_Error, Mass Balance is: " + str(sumVal))
                print("See block: " + current_block_name)
                # return 0

    for arr in large_arr:
        current_block_name = (worksheet[(get_column_letter(arr[0] - 1) +
                                         "2")].value)
        for col in arr:
            sumVal = float(0.0)  #Debug
            curr = worksheet[(get_column_letter(col) + "68")].value  #Inlet1
            if (curr != None):
                sumVal += float(curr)
            curr = worksheet[(get_column_letter(col) + "72")].value  #Inlet2
            if (curr != None):
                sumVal += float(curr)
            curr = worksheet[(get_column_letter(col) + "76")].value  #Inlet3
            if (curr != None):
                sumVal += float(curr)
            curr = worksheet[(get_column_letter(col) + "80")].value  #Inlet4
            if (curr != None):
                sumVal += float(curr)
            curr = worksheet[(get_column_letter(col) + "84")].value  #Outlet1
            if (curr != None):
                sumVal -= float(curr)
            curr = worksheet[(get_column_letter(col) + "88")].value  #Outlet2
            if (curr != None):
                sumVal -= float(curr)
            curr = worksheet[(get_column_letter(col) + "92")].value  #Outlet3
            if (curr != None):
                sumVal -= float(curr)
            curr = worksheet[(get_column_letter(col) + "96")].value  #Outlet4
            if (curr != None):
                sumVal -= float(curr)
            curr = worksheet[(get_column_letter(col) + "100")].value  #Outlet5
            if (curr != None):
                sumVal -= float(curr)
            curr = worksheet[(get_column_letter(col) + "104")].value  #Outlet6
            if (curr != None):
                sumVal -= float(curr)
            curr = worksheet[(get_column_letter(col) + "106")].value  #Work MW
            if (curr != None):
                sumVal += float(curr)
            curr = worksheet[(get_column_letter(col) + "107")].value  #Heat MW
            if (curr != None):
                sumVal += float(curr)
            writeCell = worksheet[(get_column_letter(col) + "109")]
            if (abs(sumVal) <= 1):
                writeCell.value = round_val(
                    sumVal)  #Write Cell - i.e Energy Balance
            else:
                writeCell.value = round_val(
                    sumVal)  #Write Cell - i.e Energy Balance
                print("MB_Error, Energy Balance is: " + str(sumVal))
                print("See block: " + current_block_name)
                # return 0

    for arr in large_arr:
        current_block_name = (worksheet[(get_column_letter(arr[0] - 1) +
                                         "2")].value)
        for col in arr:
            sumVal = float(0.0)
            curr = worksheet[(get_column_letter(col) + "85")].value  #Outlet1
            if (curr != None):
                sumVal += curr
            curr = worksheet[(get_column_letter(col) + "89")].value  #Outlet2
            if (curr != None):
                sumVal += curr
            curr = worksheet[(get_column_letter(col) + "93")].value  #Outlet3
            if (curr != None):
                sumVal += curr
            curr = worksheet[(get_column_letter(col) + "97")].value  #Outlet4
            if (curr != None):
                sumVal += curr
            curr = worksheet[(get_column_letter(col) + "101")].value  #Outlet5
            if (curr != None):
                sumVal += curr
            curr = worksheet[(get_column_letter(col) + "105")].value  #Outlet6
            if (curr != None):
                sumVal += curr
            curr = worksheet[(get_column_letter(col) + "69")].value  #Inlet1
            if (curr != None):
                sumVal -= curr
            curr = worksheet[(get_column_letter(col) + "73")].value  #Inlet2
            if (curr != None):
                sumVal -= curr
            curr = worksheet[(get_column_letter(col) + "77")].value  #Inlet3
            if (curr != None):
                sumVal -= curr
            curr = worksheet[(get_column_letter(col) + "81")].value  #Inlet4
            if (curr != None):
                sumVal -= curr
            curr = worksheet[(get_column_letter(col) +
                              "107")].value  #Heat Duty
            if (curr != None):
                sumVal -= curr
            writeCell = worksheet[(get_column_letter(col) + "110")]
            if (abs(sumVal) >= -1):
                writeCell.value = round_val(
                    sumVal)  #Write Cell - i.e Entropy generation
            else:
                writeCell.value = round_val(
                    sumVal
                )  #Manual bypass, should throw error according to specs
                print("Sgen_Error, Entropy Balance is: " + str(sumVal))
                print("See block: " + current_block_name)

    mod_radfrac(worksheet, large_arr)
    add_temperature(worksheet)
    return 1
Example #30
0
 def set_row_format(self, row, row_format):
     col=1
     for i in row_format:
         if i is not None:
             self.ws[get_column_letter(col)+str(row)].number_format=i
         col+=1
Example #31
0
def add_style_nqe(nqe_dataframe, PATH, dict_t0):

    wb = load_workbook(PATH)
    ws = wb['NQE Biote']
    
    nb_rows, nb_columns = nqe_dataframe.shape
    header_row = '4'
    header_columns = [get_column_letter(col_idx) for col_idx in list(range(2, nb_columns + 2))]
    borders = Border(left=Side(border_style='thin', color='FFFFFF'),
                     right=Side(border_style='thin', color='FFFFFF'),
                     top=Side(border_style='thin', color='FFFFFF'),
                     bottom=Side(border_style='thin', color='FFFFFF'))
    
    for letter in [get_column_letter(col_idx) for col_idx in range(1, nb_columns+5)]:
        for number in range(1, nb_rows+7):
            ws[letter+str(number)].border = borders
    
    t0_threshold_list = QueryScript(f" SELECT sandre, concentration_t0_max FROM {env.DATABASE_TREATED}.r3 WHERE version=  {env.CHOSEN_VERSION()}").execute()
    t0_threshold = {}
    for sandre, concentration in t0_threshold_list :
        if concentration :
            t0_threshold[sandre] = concentration

    ## UNIT 
    [unit_crustacean, sandre_crustacean, NQE_crustacean] = chemistry.get_unit_NQE(elements_crustacean.keys()) 
    parameter_crustacean = [elements_crustacean[element] for element in elements_crustacean]
    [unit_fish, sandre_fish, NQE_fish] = chemistry.get_unit_NQE(elements_fish.keys()) 
    parameter_fish = [elements_fish[element] for element in elements_fish]
    
    index = 0
    sandre_checked = sandre_crustacean
    unit_checked = unit_crustacean
    
    for letter in header_columns[5:]:
        index =None
        if ws[letter + '4'].value and int(ws[letter + '4'].value) in sandre_crustacean:
            index = sandre_crustacean.index(int(ws[letter + '4'].value))
            if not index:
               index = sandre_crustacean.index(ws[letter + '4'].value) 
            sandre_checked = sandre_crustacean
            parameter_checked = parameter_crustacean
            unit_checked = unit_crustacean
        elif ws[letter + '4'].value and int(ws[letter + '4'].value) in sandre_fish:
            index = sandre_fish.index(int(ws[letter + '4'].value))
            if not index:
               index = sandre_fish.index(ws[letter + '4'].value) 
            sandre_checked = sandre_fish
            parameter_checked = parameter_fish
            unit_checked = unit_fish
        if index!=None:
            ws[letter + '2'].value = unit_checked[index]
            ws[letter + '3'].value = sandre_checked[index]
            ws[letter + '4'].value = parameter_checked[index]           
    
    ## HEADER STYLE ##
    
    ws['B2'].value = 'Campagne'
    ws['C2'].value = '#'
    ws['D2'].value = 'Station de mesure'
    ws['E2'].value = 'Code agence'
    
    
    header_cells = [c+header_row for c in header_columns]
    header_font = Font(size=8, bold=True, name='Arial')
    header_alignment_rotate = Alignment(horizontal='center', vertical='bottom', text_rotation=90)
    header_alignment_no_rotate = Alignment(horizontal='center', vertical='bottom')
    borders = Border(left=Side(border_style='thin', color='FF000000'),
                     right=Side(border_style='thin', color='FF000000'),
                     top=Side(border_style='thin', color='FF000000'),
                     bottom=Side(border_style='thin', color='FF000000'))
    
    ws.column_dimensions['B'].width=3
    ws.column_dimensions['C'].width=3
    ws.column_dimensions['D'].width=30
    ws.column_dimensions['E'].width=8
    for letter in header_columns[:4]:
        for number in range(2,5):
            ws[letter+str(number)].border = borders
            ws[letter+str(number)].font = header_font
    ws['B2'].alignment = header_alignment_rotate
    ws['C2'].alignment = header_alignment_no_rotate
    ws['D2'].alignment = header_alignment_no_rotate
    ws['E2'].alignment = header_alignment_rotate
    
    
    
    header_font = Font(size=8, name='Arial')
    
    for letter in header_columns[4:]:
        if (ws[letter+'5'].value !=None and ws[letter+'5'].value !='') :
            
            ws.column_dimensions[letter].width=6
            ws[letter+'4'].alignment = header_alignment_rotate
            ws[letter+'4'].font = header_font
            ws[letter+'3'].alignment = header_alignment_no_rotate
            ws[letter+'3'].font = header_font
            ws[letter+'2'].alignment = header_alignment_no_rotate
            ws[letter+'2'].font = header_font
        else :
            ws.column_dimensions[letter].width=2
            
    ## ADD T0
    
    t0_mp = []
    for mp in dict_t0:
        if not dict_t0[mp]['code_t0_id'] in t0_mp and dict_t0[mp]['code_t0_id']:
            t0_mp.append(dict_t0[mp]['code_t0_id'])
    if len(t0_mp) > 1 or len(t0_mp) == 0:
        query_tuple_t0 = tuple(t0_mp)
    else:
        query_tuple_t0 = f"({t0_mp[0]})"
    reference_dict = {}
    if len(t0_mp):
        reference_result = QueryScript(f"SELECT reference, id FROM {env.DATABASE_RAW}.Measurepoint WHERE id IN {query_tuple_t0}").execute()
    else:
        reference_result = []
    for reference in reference_result:
        reference_dict.update({reference[1]:reference[0]})
    t0_result=[]
    if len(t0_mp):
        t0_result = QueryScript(f"SELECT sandre, prefix, value, Pack.measurepoint_id, Measurepoint.reference FROM {env.DATABASE_RAW}.Analysis JOIN {env.DATABASE_RAW}.Pack ON Pack.id= Analysis.pack_id JOIN {env.DATABASE_RAW}.Measurepoint ON Pack.measurepoint_id=Measurepoint.id WHERE Pack.measurepoint_id IN {query_tuple_t0};").execute()
    dict_t0_result= {}
    for element in t0_result:
        if not element[3] in dict_t0_result:
            dict_t0_result.update({element[3]: {element[0]:element[1] + str(element[2]) if element[1] else str(element[2]), 'reference': element[4]}})
        else :
            dict_t0_result[element[3]][element[0]] = element[1] + str(element[2]) if element[1] else str(element[2])
    
    t0_font = Font(size=6, name='Arial')
    t0_border = Border(left=Side(border_style='thin', color='000000'),
                     right=Side(border_style='thin', color='000000'),
                     top=Side(border_style='thin', color='000000'),
                     bottom=Side(border_style='thin', color='000000'))
    t0_not_valid = Border(left=Side(border_style='medium', color='FF0000'),
                     right=Side(border_style='medium', color='FF0000'),
                     top=Side(border_style='medium', color='FF0000'),
                     bottom=Side(border_style='medium', color='FF0000'))

    body_alignment = Alignment(horizontal='center', vertical='center')
    
    for index, t0 in enumerate(t0_mp):
        ws['B'+str(nb_rows+5+index)].font = t0_font
        ws['B'+str(nb_rows+5+index)].border = t0_border
        ws['C'+str(nb_rows+5+index)].font = t0_font
        ws['C'+str(nb_rows+5+index)].border = t0_border
        ws['D'+str(nb_rows+5+index)].font = t0_font
        ws['D'+str(nb_rows+5+index)].border = t0_border
        if t0 in dict_t0_result :
            ws['D'+str(nb_rows+5+index)].value = dict_t0_result[t0]['reference']
        else :
            ws['D'+str(nb_rows+5+index)].value = reference_dict[t0]
        ws['E'+str(nb_rows+5+index)].font = t0_font
        ws['E'+str(nb_rows+5+index)].border = t0_border
        for letter in header_columns[5:]:
            sandre = ws[letter +'3'].value
            if t0 in dict_t0_result and str(sandre) in dict_t0_result[t0]:
                ws[letter+str(nb_rows+5+index)].value = dict_t0_result[t0][str(sandre)]
                if str(sandre) in t0_threshold and str(dict_t0_result[t0][str(sandre)])[0]!='<' and float(dict_t0_result[t0][str(sandre)]) > t0_threshold[str(sandre)] :
                    ws[letter+str(nb_rows+5+index)].border = t0_not_valid
                else :
                    ws[letter+str(nb_rows+5+index)].border = t0_border
                ws[letter+str(nb_rows+5+index)].font = t0_font
                ws[letter+str(nb_rows+5+index)].alignment = body_alignment
                
            elif sandre != None :
                ws[letter+str(nb_rows+5+index)].value = 'ND'
                ws[letter+str(nb_rows+5+index)].font = t0_font
                ws[letter+str(nb_rows+5+index)].border = t0_border
                ws[letter+str(nb_rows+5+index)].alignment = body_alignment
        

    ## BODY STYLE ##
    body_rows = [str(r) for r in list(range(5, nb_rows + 5 + len(t0_mp)))]
    body_columns = header_columns[5:]

    body_font = Font(size=6, name='Arial')
    body_fill_ok = PatternFill(fill_type='solid', start_color='318CE7', end_color='318CE7')
    body_fill_nd = PatternFill(fill_type='solid', start_color='FFFFFF', end_color='FFFFFF')
    body_fill_not_ok = PatternFill(fill_type='solid', start_color='BB0B0B', end_color='BB0B0B')
    body_alignment = Alignment(horizontal='center', vertical='center')

    for column in header_columns:
        for row in body_rows:
            if column in ['B','C','D','E']:
                ws[column+row].border = borders
                ws[column+row].font = body_font


    for column in body_columns:
        sandre_checked = ws[column+'3'].value
        if sandre_checked!='' and sandre_checked!=None:
            try :
                index = sandre_crustacean.index(sandre_checked)
                threshold = NQE_crustacean[index]
            except :
                threshold = ''
        for row in body_rows:
            cell = ws[column+row]
            value = cell.value
            cell.font = body_font
            if value!=None :
                cell.alignment = body_alignment
                if (value!="ND" and value!='0.0' and threshold!='') and ((value!='' and value[0]=='<') or float(value)<threshold):
                    cell.fill = body_fill_ok
                elif (value!="ND" and value!='0.0' and threshold!='' and float(value)>=threshold):
                    cell.fill = body_fill_not_ok
    for index,mp in enumerate(dict_t0):
        try :
            if ws[header_columns[-1] + str(index+5)].value and ws[header_columns[-1] + str(index+5)].value in dict_t0:
                index_t0_associated = t0_mp.index(dict_t0[ws[header_columns[-1] + str(index+5)].value]['code_t0_id'])
                for column in header_columns[5:]:
                    t0_ok = True if ws[column + str(5+nb_rows+index_t0_associated)].border != t0_not_valid else False 
                    if ws[column + str(5+nb_rows+index_t0_associated)].value!= None and ws[column + str(5+nb_rows+index_t0_associated)].value!= '':
                        if not t0_ok :
                            ws[column + str(5+index)].border = t0_not_valid
                            ws[column + str(5+index)].font = body_font
                        else :
                            ws[column + str(5+index)].border = borders
                            ws[column + str(5+index)].font = body_font

        except ValueError :
            for column in header_columns[5:]:
                ws[column + str(5+index)].border = borders
                ws[column + str(5+index)].font = body_font

    ws.delete_cols(len(header_columns)+1,1)
    
    for letter in header_columns[5:]:
        for number in range(5, nb_rows+21):
                ws[letter + str(number)].value = str(ws[letter + str(number)].value).replace(".", ",") if ws[letter + str(number)].value else ''
    ws.freeze_panes = ws["F6"]
    wb.save(PATH)
    wb.close()

    wb = load_workbook(PATH)
    ws = wb['NQE Biote']

    ## Add threshold table
    ws.insert_rows(1)
    ws.insert_rows(1)


    ws["F2"].value = "Seuil NQE"

    
    ws.column_dimensions['F'].width=10
    for letter in header_columns[5:]:
        if ws[letter + "5"].value :
            try :
                index_found = sandre_crustacean.index(ws[letter + "5"].value)
                NQE_found = NQE_crustacean[index_found]
                ws[letter+"1"].border = borders
                ws[letter+"2"].value = NQE_found
                ws[letter+"2"].border = borders
            except ValueError :
                try :
                    index_found = sandre_fish.index(ws[letter + "5"].value)
                    NQE_found = NQE_fish[index_found]
                    ws[letter+"1"].border = borders
                    ws[letter+"2"].value = NQE_found
                    ws[letter+"2"].border = borders
                except ValueError :
                    continue



    ## Merge unit
    
    current_unit = ws['G4'].value 
    first_letter = 'G'           
    last_letter = 'G'           
    index = 6
    while index <len(header_columns): 
        while index <len(header_columns) and ws[header_columns[index] + '4'].value == current_unit :   
            last_letter = header_columns[index]
            index +=1
        ws.merge_cells(first_letter + '4:'+last_letter+'4')
        if index<len(header_columns):
            first_letter = last_letter = header_columns[index]
        current_unit = ws[first_letter +'4'].value
        index+=1
    
    first_letter = 'G'           
    last_letter = 'G'           
    index = 6
    while index <len(header_columns)-1: 
        while index <len(header_columns) and ws[header_columns[index] + '5'].value in elements_crustacean or ws[header_columns[index] + '5'].value in elements_fish  :   
            last_letter = header_columns[index]
            index +=1
        if ws[header_columns[index-1] + '5'].value in elements_crustacean :
            ws[first_letter+'1'].value = 'NQE Crustacé' 
            ws.merge_cells(first_letter + '1:'+last_letter+'1')
        elif ws[header_columns[index-1] + '5'].value in elements_fish :
            ws[first_letter+'1'].value = 'NQE Poisson' 
            ws.merge_cells(first_letter + '1:'+last_letter+'1')
        if index<len(header_columns)-1:
            index+=1
            first_letter = last_letter = header_columns[index]

    ws.merge_cells('B4:B6')
    ws.merge_cells('C4:C6')
    ws.merge_cells('D4:D6')
    ws.merge_cells('E4:E6')

    wb.save(PATH)
    wb.close()
Example #32
0
def export_nach_excel(namedtuple_in: namedtuple,
                      detail_name: str,
                      data_list: list,
                      filename_postfix="",
                      filename_in=None,
                      mappings=dict(),
                      export_name=None,
                      export_beschreibung=None):
    if filename_in is None:
        if export_name is None:
            # Export Name aus Nametuple ableiten
            export_name = namedtuple_in.__name__.capitalize()
        export_beschreibung = None
    else:
        if export_name is not None or export_beschreibung is not None:
            raise RuntimeError(
                "'filename_in' und 'export_name' oder 'export_beschreibung' "
                "dürfen nicht zusammen angegeben werden!")
        # filename_in wird verwendet um
        # 1. den ersten Teil bis zum " " als echten Dateinamen zu verwenden
        # 2. eine zusätzliche Infozeile auszugeben
        # Hinweis: bei zu langen Dateinamen unter Windows/Excel, kommt es zu einer kaputten Excel Datei,
        # die beim Öffnen dann immer zuerst autom. durch Excel repariert werden muss
        if "~" in filename_in:
            # Filename~Export Name~Beschreibung
            export_name = filename_in.split("~")[0]
            export_beschreibung = filename_in.split(
                "~")[1] + ": " + filename_in.split("~")[2]
        else:
            export_name = filename_in if " " not in filename_in else filename_in.split(
                " ")[0]
            export_beschreibung = filename_in

    timestamp = datetime.datetime.now().strftime("_Export_%Y-%m-%d_%H_%M")
    filename = "{}_{}_{}_{}.xlsx".format(filename_postfix, export_name,
                                         detail_name, timestamp)
    filename = re.sub(r'^_', '', filename)
    filename = filename.replace(" ", "_")
    filename = re.sub(r'_{2,9}', '_', filename)

    temp_dir = tempfile.gettempdir()
    export_file_path = os.path.join(temp_dir, filename)

    wb = Workbook()
    ws = wb.active
    ws.title = export_name

    column_header = PatternFill(start_color='AAAAAA',
                                end_color='AAAAAA',
                                fill_type='solid')

    if export_beschreibung is not None:
        row = 4
        ws.cell(column=1, row=1, value=export_beschreibung)
        ws.cell(column=1,
                row=2,
                value="Datum: {}".format(
                    datetime.datetime.now().strftime("%d.%m.%Y %H:%M")))
        ws.merge_cells('A1:H1')
        ws.merge_cells('A2:H2')
    else:
        row = 1

    column = 1
    for name in namedtuple_in._fields:
        ws.cell(column=column, row=row, value=name.capitalize())
        col = ws["{}{}".format(get_column_letter(column), row)]
        col.font = Font(bold=True)
        col.fill = column_header
        column += 1

    row += 1
    for data in data_list:
        column = 1
        for name, value in data._asdict().items():
            try:
                if name in mappings:
                    mapped_value = mappings[name](value)
                else:
                    mapped_value = map_str_value(value)
            except Exception:
                logger.warning(
                    "Fehler bei mapped_value, Wert: '{}'".format(value))
                mapped_value = value

            cell = ws.cell(column=column, row=row, value=mapped_value)
            if isinstance(mapped_value, datetime.date):
                cell.number_format = 'DD.MM.YYYY'
            column += 1
        row += 1

    wb.save(filename=export_file_path)
    return export_file_path
Example #33
0
            elif a == 'CPD':
                a = "CPD(承诺交单日期)"
                CPDPos = x.column
            elif a == '国家':
                CountryPos = x.column
            elif a == '备货单':  #备货单和整机标识,通常二选一
                BillPos = x.column
            elif a == '整机标识':
                WholeDevicePos = x.column
        content1.append(a)
#第一行遍历完,到最后一列
    print(BillPos)
    if x.row == 1:
        content1.extend(['version', 'IsMain', 'Date', 'Site', 'Region'])
    else:
        b = get_column_letter(VerCodePos) + str(x.row)
        a = "=VLOOKUP({0}, '{1}'!C2:F5, 4, FALSE)".format(b, FileNameVerList)
        content1.append(a)

        a = "=VLOOKUP({0}, '{1}'!C2:F5, 2, FALSE)".format(b, FileNameVerList)
        content1.append(a)

        b = get_column_letter(ASDPos) + str(x.row)
        a = "=TEXT({0},\"YYYY/MM\")".format(b)
        content1.append(a)
        if BillPos != 0:
            b = get_column_letter(BillPos) + str(x.row)
            a = "=VLOOKUP({0}, L{1}:L5, 1, FALSE)".format(b, x.row)
        content1.append(a)

        b = get_column_letter(CountryPos) + str(x.row)
Example #34
0
 def set_cell_value(self, row, col, value):
     col_letter = get_column_letter(col)
     self.ws[str(col_letter) + str(row)] = value
Example #35
0
def write_common(sheet, report_dict):
    title = 'Общие метрики'
    subtitles = ['', 'Сессии', 'Заказы', 'Выручка', 'Конверсия', 'RPS', 'AOV']
    row_names = [
        'Всего', 'Сессии без поиска', 'Сессии с поиском', 'С поиском / Всего'
    ]
    cells = {
        key: report_dict[key]
        for key in {
            'orders_total', 'revenue_total', 'sessions_total',
            'autocomplete_and_search_sessions_total',
            'autocomplete_and_search_sessions_revenue',
            'autocomplete_and_search_sessions_orders_total'
        }
    }
    # styling title
    sheet['A1'] = title
    sheet['A1'].style = 'title'
    sheet.merge_cells('A1:G1')

    # styling subtitle
    for s_row in range(2, 3):
        for s_col in range(1, 8):
            s_ind = get_column_letter(s_col) + str(s_row)
            sheet[s_ind] = subtitles[s_col - 1]
            sheet[s_ind].style = 'subtitle'

    # styling percents
    for pc_row in range(3, 6):
        sheet['E' + str(pc_row)].number_format = '0.00%'
    for pc_col in range(2, 5):
        sheet[get_column_letter(pc_col) + '6'].number_format = '0.00%'

    # styling floats
    for fl_row in range(3, 6):
        for fl_col in range(6, 8):
            fl_ind = get_column_letter(fl_col) + str(fl_row)
            sheet[fl_ind].number_format = '#,##0.00'

    # writing row names
    for rn_row in range(3, 7):
        sheet['A' + str(rn_row)] = row_names[rn_row - 3]

    # total
    sheet['B3'] = cells['sessions_total']
    sheet['C3'] = cells['orders_total']
    sheet['D3'] = cells['revenue_total']
    try:
        sheet['E3'] = round(sheet['C3'].value / sheet['B3'].value)
    except ZeroDivisionError:
        sheet['E3'] = 0
    try:
        sheet['F3'] = round(sheet['D3'].value / sheet['B3'].value, 2)
    except ZeroDivisionError:
        sheet['F3'] = 0
    try:
        sheet['G3'] = round(sheet['D3'].value / sheet['C3'].value, 2)
    except ZeroDivisionError:
        sheet['G3'] = 0

    # sessions without search
    sheet['B4'] = cells['sessions_total'] - cells[
        'autocomplete_and_search_sessions_total']
    sheet['C4'] = cells['orders_total'] - cells[
        'autocomplete_and_search_sessions_orders_total']
    sheet['D4'] = cells['revenue_total'] - cells[
        'autocomplete_and_search_sessions_revenue']
    try:
        sheet['E4'] = round(sheet['C4'].value / sheet['B4'].value, 2)
    except ZeroDivisionError:
        sheet['E4'] = 0
    try:
        sheet['F4'] = round(sheet['D4'].value / sheet['B4'].value, 2)
    except ZeroDivisionError:
        sheet['F4'] = 0
    try:
        sheet['G4'] = round(sheet['D4'].value / sheet['C4'].value, 2)
    except ZeroDivisionError:
        sheet['G4'] = 0

    # sessions with search
    sheet['B5'] = cells['autocomplete_and_search_sessions_total']
    sheet['C5'] = cells['autocomplete_and_search_sessions_orders_total']
    sheet['D5'] = cells['autocomplete_and_search_sessions_revenue']
    try:
        sheet['E5'] = round(sheet['C5'].value / sheet['B5'].value, 2)
    except ZeroDivisionError:
        sheet['E5'] = 0
    try:
        sheet['F5'] = round(sheet['D5'].value / sheet['B5'].value, 2)
    except ZeroDivisionError:
        sheet['F5'] = 0
    try:
        sheet['G5'] = round(sheet['D5'].value / sheet['C5'].value, 2)
    except ZeroDivisionError:
        sheet['G5'] = 0

    # with search / total
    try:
        sheet['B6'] = round(
            cells['autocomplete_and_search_sessions_total'] /
            cells['sessions_total'], 2)
    except ZeroDivisionError:
        sheet['B6'] = 0
    try:
        sheet['C6'] = round(
            cells['autocomplete_and_search_sessions_orders_total'] /
            cells['orders_total'], 2)
    except ZeroDivisionError:
        sheet['C6'] = 0
    try:
        sheet['D6'] = round(
            cells['autocomplete_and_search_sessions_revenue'] /
            cells['revenue_total'], 2)
    except ZeroDivisionError:
        sheet['D6'] = 0
Example #36
0
import openpyxl
import sys
from openpyxl.utils.cell import get_column_letter

if len(sys.argv) < 2:
    print('usage: py transposition.py [xlsx]')
    exit()

xlsxFile = sys.argv[1]

# Open xlsx and read it
wbRead = openpyxl.load_workbook(xlsxFile)
sheetRead = wbRead.get_active_sheet()

# Create sheet to be write
wbWrite = openpyxl.Workbook()
sheetWrite = wbWrite.get_active_sheet()

# Transposition
for i in range(1, sheetRead.max_row+1):
    for j in range(1, sheetRead.max_column+1):
        coordRead = get_column_letter(j)+str(i)
        coordWrite = get_column_letter(i)+str(j)
        sheetWrite[coordWrite] = sheetRead[coordRead].value

# save sheet to file
wbWrite.save(xlsxFile+'.trans.xlsx')


wb = Workbook()
ws = wb.active
 
for r_idx, row in enumerate(rows, 1):
    for c_idx, value in enumerate(row, 1):
        ws.cell(row=r_idx, column=c_idx, value=value)
 
# Set column widths based on title width or fixed number
widths = {}
for column in ws.columns:
    if column[0].value is None: # no column header => Fixed with
        widths[column[0].column] = 10.5
    else: # if column header is present => min width resp. maximum
        widths[column[0].column] = max(len(str(column[0].value)) * 1.45, 10.5)
 
ws.column_dimensions[get_column_letter(column[0].column)].width = widths[column[0].column]
 
# Insert formatted table from A1 to max column/max row
tab = Table(displayName="MeineTabelle", ref='A1:' + get_column_letter(ws.max_column) + str(ws.max_row))
style = TableStyleInfo(name="TableStyleLight9", showFirstColumn=False,
                       showLastColumn=False, showRowStripes=True, showColumnStripes=True)
tab.tableStyleInfo = style
ws.add_table(tab)
 
# conditional formatting
redFill = PatternFill(start_color='EE1111',end_color='EE1111',fill_type='solid')
greenFill = PatternFill(start_color='EE1111',end_color='11EE11',fill_type='solid')
ws.conditional_formatting.add('A2:B'+str(ws.max_row),CellIsRule(operator='equal', formula=[1], stopIfTrue=True, fill=greenFill))
ws.conditional_formatting.add('A2:B'+str(ws.max_row),CellIsRule(operator='notEqual', formula=[1], stopIfTrue=True, fill=redFill))
 
lightbluefill = PatternFill(start_color='CCCCFF',end_color='CCCCFF',fill_type='solid')
Example #38
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, 8):
        ws.row_dimensions[i].height = 42

    # for i in range(2, 6 + 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('V')):
        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['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~ table_data
    ################################################
    has_data_flag = True
    reporting_period_data = report['reporting_period']
    if "names" not in reporting_period_data.keys() or \
            reporting_period_data['names'] is None or \
            len(reporting_period_data['names']) == 0:
        has_data_flag = False

    if "timestamps" not in reporting_period_data.keys() or \
            reporting_period_data['timestamps'] is None or \
            len(reporting_period_data['timestamps']) == 0:
        has_data_flag = False

    if "values" not in reporting_period_data.keys() or \
            reporting_period_data['values'] is None or \
            len(reporting_period_data['values']) == 0:
        has_data_flag = False
    ca = reporting_period_data['names']
    ca_len = len(ca)
    temp_max_row = 0
    times = reporting_period_data['timestamps']
    category = report['meter']['energy_category_name']
    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 = 9 + (parameters_parameters_datas_len + ca_len) * 6
    if has_data_flag:
        time = times[0]
        for time in times:
            if len(time) > 0:
                break
        has_data = False
        max_row = 0
        current_sheet_parameters_row_number = 7
        temp_max_row = max_row
        for i in range(8, len(time) + 6 + ca_len * 6 + len(category) * 6 + 2):
            ws.row_dimensions[i].height = 42
        if len(time) > 0:
            has_data = True
            current_sheet_parameters_row_number = 7 + ca_len * 6
        if has_data:

            max_row = start_detail_data_row_num + len(time)
            # print("max_row", max_row)
            ws['B6'].font = title_font
            ws['B6'] = name + ' 趋势'

            ws.row_dimensions[start_detail_data_row_num - 1].height = 60
            ws['B' + str(start_detail_data_row_num - 1)].fill = table_fill
            ws['B' + str(start_detail_data_row_num - 1)].font = title_font
            ws['B' + str(start_detail_data_row_num - 1)].border = f_border
            ws['B' + str(start_detail_data_row_num - 1)].alignment = c_c_alignment
            ws['B' + str(start_detail_data_row_num - 1)] = '日期时间'

            for i in range(0, len(time)):
                col = 'B'
                row = str(start_detail_data_row_num + 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 = format_cell.get_column_letter(3 + i)

                ws[col + str(start_detail_data_row_num - 1)].fill = table_fill
                ws[col + str(start_detail_data_row_num - 1)].font = title_font
                ws[col + str(start_detail_data_row_num - 1)].alignment = c_c_alignment
                ws[col + str(start_detail_data_row_num - 1)] = reporting_period_data['names'][i]
                ws[col + str(start_detail_data_row_num - 1)].border = f_border

                for j in range(0, len(time)):

                    row = str(start_detail_data_row_num + 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], 3) if \
                        len(reporting_period_data['values'][i]) > 0 and \
                        reporting_period_data['values'][i][j] is not None else " "
                    ws[col + row].border = f_border
            # line
            # 39~: line
                line = LineChart()
                line.title = '趋势值 - ' + reporting_period_data['names'][i]
                labels = Reference(ws, min_col=2, min_row=start_detail_data_row_num, max_row=max_row-1)
                line_data = Reference(ws, min_col=3 + i, min_row=start_detail_data_row_num+1, max_row=max_row-1)
                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 = 36
                # pie.title = "Pies sold by category"
                line.dLbls = DataLabelList()
                # line.dLbls.showCatName = True  # label show
                line.dLbls.dLblPos = 't'
                line.dLbls.showVal = False  # val show
                line.dLbls.showPercent = False  # percent show
                # s1 = CharacterProperties(sz=1800)     # font size *100
                chart_col = chr(ord('B'))
                chart_cell = chart_col + str(7 + 6*i)

                ws.add_chart(line, chart_cell)
    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

    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['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 #39
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, 2000 + 1):
        ws.row_dimensions[i].height = 42

    # Col width
    ws.column_dimensions['A'].width = 1.5
    ws.column_dimensions['B'].width = 20.0
    ws.column_dimensions['C'].width = 20.0

    for i in range(ord('D'), ord('I')):
        ws.column_dimensions[chr(i)].width = 15.0

    # Font
    name_font = Font(name='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=True,
                              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:I3")
    for i in range(ord('G'), ord('I') + 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], 2)
            ws[col + '8'].border = f_border

            ws[col + '9'].font = name_font
            ws[col + '9'].alignment = c_c_alignment
            ws[col + '9'] = round(reporting_period_data['subtotals_per_unit_area'][i], 2)
            ws[col + '9'].border = f_border

            ws[col + '10'].font = name_font
            ws[col + '10'].alignment = c_c_alignment
            ws[col + '10'] = str(round(reporting_period_data['increment_rates'][i] * 100, 2)) + "%" \
                if reporting_period_data['increment_rates'][i] is not None else "-"
            ws[col + '10'].border = f_border

        end_col = chr(ord(col)+1)
        ws[end_col + '7'].fill = table_fill
        ws[end_col + '7'].font = name_font
        ws[end_col + '7'].alignment = c_c_alignment
        ws[end_col + '7'] = "总计 (" + reporting_period_data['total_unit'] + ")"
        ws[end_col + '7'].border = f_border

        ws[end_col + '8'].font = name_font
        ws[end_col + '8'].alignment = c_c_alignment
        ws[end_col + '8'] = round(reporting_period_data['total'], 2)
        ws[end_col + '8'].border = f_border

        ws[end_col + '9'].font = name_font
        ws[end_col + '9'].alignment = c_c_alignment
        ws[end_col + '9'] = round(reporting_period_data['total_per_unit_area'], 2)
        ws[end_col + '9'].border = f_border

        ws[end_col + '10'].font = name_font
        ws[end_col + '10'].alignment = c_c_alignment
        ws[end_col + '10'] = str(round(reporting_period_data['total_increment_rate'] * 100, 2)) + "%" \
            if reporting_period_data['total_increment_rate'] is not None else "-"
        ws[end_col + '10'].border = f_border

    else:
        for i in range(6, 10 + 1):
            ws.row_dimensions[i].height = 0.1

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

    has_ele_peak_flag = True
    if "toppeaks" not in reporting_period_data.keys() or \
            reporting_period_data['toppeaks'] is None or \
            len(reporting_period_data['toppeaks']) == 0:
        has_ele_peak_flag = False

    if has_ele_peak_flag:
        ws['B12'].font = title_font
        ws['B12'] = name+' 分时电耗'

        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()
        labels = Reference(ws, min_col=2, min_row=14, max_row=17)
        pie_data = Reference(ws, min_col=3, min_row=13, max_row=17)
        pie.add_data(pie_data, titles_from_data=True)
        pie.set_categories(labels)
        pie.height = 5.25
        pie.width = 8
        s1 = pie.series[0]
        s1.dLbls = DataLabelList()
        s1.dLbls.showCatName = False
        s1.dLbls.showVal = True
        s1.dLbls.showPercent = True
        ws.add_chart(pie, "D13")

    else:
        for i in range(12, 18 + 1):
            ws.row_dimensions[i].height = 0.1

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

    current_row_number = 19

    has_subtotals_data_flag = True
    if "subtotals" not in reporting_period_data.keys() or \
            reporting_period_data['subtotals'] is None or \
            len(reporting_period_data['subtotals']) == 0:
        has_subtotals_data_flag = False

    if has_subtotals_data_flag:
        ws['B' + str(current_row_number)].font = title_font
        ws['B' + str(current_row_number)] = name + ' 成本占比'

        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 = 8
        s1 = pie.series[0]
        s1.dLbls = DataLabelList()
        s1.dLbls.showCatName = False
        s1.dLbls.showVal = True
        s1.dLbls.showPercent = True
        table_cell = 'D' + str(table_start_row_number)
        ws.add_chart(pie, table_cell)

        if ca_len < 4:
            current_row_number = current_row_number - ca_len + 4

    else:
        for i in range(21, 29 + 1):
            current_row_number = 30
            ws.row_dimensions[i].height = 0.1

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

    has_detail_data_flag = True

    table_start_draw_flag = current_row_number + 1

    if "timestamps" not in reporting_period_data.keys() or \
            reporting_period_data['timestamps'] is None or \
            len(reporting_period_data['timestamps']) == 0:
        has_detail_data_flag = False

    if has_detail_data_flag:
        reporting_period_data = report['reporting_period']
        times = reporting_period_data['timestamps']
        ca_len = len(report['reporting_period']['names'])
        parameters_names_len = len(report['parameters']['names'])
        parameters_parameters_datas_len = 0
        for i in range(0, parameters_names_len):
            if len(report['parameters']['timestamps'][i]) == 0:
                continue
            parameters_parameters_datas_len += 1
        detail_data_table_start_row_number = current_row_number + (ca_len + parameters_parameters_datas_len) * 6 + 3

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

        current_row_number = detail_data_table_start_row_number

        time = times[0]
        has_data = False

        if len(time) > 0:
            has_data = True

        if has_data:

            ws['B' + str(current_row_number)].fill = table_fill
            ws['B' + str(current_row_number)].border = f_border
            ws['B' + str(current_row_number)].font = title_font
            ws['B' + str(current_row_number)].alignment = c_c_alignment
            ws['B' + str(current_row_number)] = '日期时间'

            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], 2)
                    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, 2)
                ws[end_col + str(current_row_number)].border = f_border

                current_row_number += 1

            table_end_row_number = current_row_number - 1

            ws['B' + str(current_row_number)].font = title_font
            ws['B' + str(current_row_number)].alignment = c_c_alignment
            ws['B' + str(current_row_number)] = '小计'
            ws['B' + str(current_row_number)].border = f_border

            col = 'B'

            format_time_width_number = 1.0
            min_len_number = 1.0
            min_width_number = 11.0  # 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):
                col = chr(ord('C') + i)
                ws[col + str(current_row_number)].font = title_font
                ws[col + str(current_row_number)].alignment = c_c_alignment
                ws[col + str(current_row_number)] = round(reporting_period_data['subtotals'][i], 2)
                ws[col + str(current_row_number)].border = f_border

                line = LineChart()
                line.title = '报告期成本 - ' + \
                             reporting_period_data['names'][i] + " (" + reporting_period_data['units'][i] + ")"
                labels = Reference(ws, min_col=2, min_row=detail_data_table_start_row_number + 1,
                                   max_row=table_end_row_number)
                line_data = Reference(ws, min_col=3 + i, min_row=detail_data_table_start_row_number,
                                      max_row=table_end_row_number)
                line.add_data(line_data, titles_from_data=True)
                line.set_categories(labels)
                line_data = line.series[0]
                line_data.marker.symbol = "circle"
                line_data.smooth = True
                line.height = 8.25
                line.width = format_time_width_number * len(time) if len(time) > min_len_number else min_width_number
                if line.width > 24:
                    line.width = 24
                line.x_axis.crosses = 'min'
                line.dLbls = DataLabelList()
                line.dLbls.dLblPos = 't'
                line.dLbls.showVal = True
                line.dLbls.showPercent = False
                chart_col = 'B'
                chart_cell = chart_col + str(table_start_draw_flag + 6 * i)
                ws.add_chart(line, chart_cell)

            end_col = chr(ord(col) + 1)
            ws[end_col + str(current_row_number)].font = title_font
            ws[end_col + str(current_row_number)].alignment = c_c_alignment
            ws[end_col + str(current_row_number)] = round(reporting_period_data['total'], 2)
            ws[end_col + str(current_row_number)].border = f_border

            current_row_number += 1

    else:
        for i in range(30, 69 + 1):
            current_row_number = 70
            ws.row_dimensions[i].height = 0.1

    ##########################################
    has_parameters_names_and_timestamps_and_values_data = True

    ca_len = len(report['reporting_period']['names'])
    current_sheet_parameters_row_number = table_start_draw_flag + ca_len * 6
    if 'parameters' not in report.keys() or \
            report['parameters'] is None or \
            'names' not in report['parameters'].keys() or \
            report['parameters']['names'] is None or \
            len(report['parameters']['names']) == 0 or \
            'timestamps' not in report['parameters'].keys() or \
            report['parameters']['timestamps'] is None or \
            len(report['parameters']['timestamps']) == 0 or \
            'values' not in report['parameters'].keys() or \
            report['parameters']['values'] is None or \
            len(report['parameters']['values']) == 0 or \
            timestamps_data_all_equal_0(report['parameters']['timestamps']):
        has_parameters_names_and_timestamps_and_values_data = False
    if has_parameters_names_and_timestamps_and_values_data:

        ###############################
        # new worksheet
        ###############################

        parameters_data = report['parameters']

        parameters_names_len = len(parameters_data['names'])

        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