Пример #1
0
def layout_example1():

    df = pd.DataFrame(dict(a=[10, 20, 30, 40, 50], b=[0.1, 0.9, 0.2, 0.6,
                                                      0.3]),
                      index=[1, 2, 3, 4, 5])

    def style_func(idx, col):
        if col == 'b':
            return OpenPyxlStyleHelper.get_style(number_format='0.00%')
        else:
            # for 'a' we do dollar format
            return OpenPyxlStyleHelper.get_style(number_format='$#,##.00')

    # create a presentation model
    # note the OpenPyxlStyleHeloer function available in xlsx_styles module. But a return value of style function
    # can be any dict whose keys are attributes of the OpenPyxl cell object.
    presentation_model = build_presentation_model(
        df=df,
        data_value_func=lambda idx, col: df.loc[idx, col] * 10
        if col == 'a' else df.loc[idx, col],
        data_style_func=style_func,
        header_value_func=lambda node: node.value.capitalize(),
        header_style_func=lambda _: OpenPyxlStyleHelper.default_header_style(),
        index_value_func=lambda node: node.value * 100,
        index_style_func=lambda _: OpenPyxlStyleHelper.default_header_style(),
        index_name_func=lambda _: 'Basic Example',
        index_name_style_func=lambda _: OpenPyxlStyleHelper.
        default_header_style())

    # start_layout_code_1
    # create a layout, which is usually a nested list of presentation models
    layout = [[presentation_model], [[presentation_model],
                                     [presentation_model]]]

    # render to xlsx
    output_fp = os.path.join(tempfile.gettempdir(),
                             'layout_vertical_example1.xlsx')
    # the default value for orientation is 'vertical'
    XLSXWriter.to_xlsx(layout, output_fp=output_fp, orientation='vertical')

    output_fp = os.path.join(tempfile.gettempdir(),
                             'layout_horizontal_example1.xlsx')
    XLSXWriter.to_xlsx(layout, output_fp=output_fp, orientation='horizontal')
    print('Writing xlsx file=', output_fp)

    # mutiple nesting
    layout_complex = [
        presentation_model,
        [presentation_model, [presentation_model, presentation_model]]
    ]

    output_fp = os.path.join(tempfile.gettempdir(),
                             'layout_complex_example1.xlsx')
    XLSXWriter.to_xlsx(layout_complex,
                       output_fp=output_fp,
                       orientation='vertical')
    print('Writing xlsx file=', output_fp)