pandas 출력 excel 파일에 헤더 제목, 스타일 장식기 추가

2666 단어 python3pandas
다음 장식기는 스타일이 있는 excel 파일을 출력합니다. 
import os
import pandas as pd
from xlsxwriter.utility import xl_range


def decoratorToExcel(excel_name: str = "test", excel_title: str = "test", excel_dir: str = None):
    """
     , 
    :param excel_dir:  
    :param excel_title:  
    :param excel_name:  
    :return:
    """

    def midFunc(cls_func):

        def inner(self, *args, **kwargs):
            data: pd.DataFrame = cls_func(self, *args, **kwargs)
            try:
                if excel_dir:
                    os.makedirs(excel_dir)
            except BaseException:
                pass
            writer = pd.ExcelWriter(
                '%s%s.xlsx' % (
                    excel_dir + "/" if excel_dir else "", excel_name,), datetime_format='yyyy/mm/dd')
            data.to_excel(
                writer,
                engine='xlsxwriter',
                sheet_name='sheet',
                startrow=2,
                header=False,
                float_format="%.2f")
            workbook = writer.book
            worksheet = writer.sheets['sheet']
            worksheet.set_row(0, 20)
            worksheet.set_row(1, 30)
            header_format = workbook.add_format({
                'bold': True,
                'font_color': 'black',
                'text_wrap': True,
                'align': 'center',
                'fg_color': '#6BA81E',
                'border': 1})
            rl = data.columns.tolist()
            rl.insert(0, ' ')
            cell_range = xl_range(0, 0, 0, len(rl) - 1)
            merge_format = workbook.add_format(
                {'align': 'center', 'bold': True, 'fg_color': '#009688', 'font_color': "#000000"})
            worksheet.merge_range(cell_range, excel_title, merge_format)
            for col_num, value in enumerate(rl):
                worksheet.write(1, col_num, value, header_format)
            writer.save()
            return

        return inner

    return midFunc


class Test:

    @decoratorToExcel(excel_name=" ", excel_title=" sheet")
    def setExcelData(self) -> pd.DataFrame:
        """
         excel 
        :return: DataFrame
        """
        data: pd.DataFrame = pd.DataFrame({"name": "     ".split(), "age": "12 13 15".split()})
        return data


if __name__ == '__main__':
    Test().setExcelData()

 

좋은 웹페이지 즐겨찾기