如何将pandas df保存到excel表格然后格式化?

时间:2018-02-14 21:42:35

标签: python excel pandas format xlsxwriter

import pandas as pd

from datetime import datetime, date

df = pd.DataFrame({'Date and time': [datetime(2015, 1, 1, 11, 30, 55),
                                 datetime(2015, 1, 2, 1,  20, 33),
                                 datetime(2015, 1, 3, 11, 10    ),
                                 datetime(2015, 1, 4, 16, 45, 35),
                                 datetime(2015, 1, 5, 12, 10, 15)],
                   'Dates only':    [date(2015, 2, 1),
                                 date(2015, 2, 2),
                                 date(2015, 2, 3),
                                 date(2015, 2, 4),
                                 date(2015, 2, 5)],
               })

writer = pd.ExcelWriter("pandas_datetime_format.xlsx",
                    engine='xlsxwriter',
                    datetime_format='mmm d yyyy hh:mm:ss',
                    date_format='mmmm dd yyyy')

df.to_excel(writer, sheet_name='Sheet1')

workbook  = writer.book
worksheet = writer.sheets['Sheet1']

format_bc = workbook.add_format({
    'font_name': 'Arial',
    'font_size' : 14,
    'font_color': 'white',
    'bold': 0,
    'border': 1,
    'align': 'left',
    'valign': 'vcenter',
    'text_wrap': 1,
    'fg_color': '#005581'})
worksheet.set_column('B:C', 20, format_bc)
writer.save()

上述代码有望生成格式化的Excel工作表,其中B列和B列具有蓝色背景和format_bc中指定的其他方面。 相反,我收到了下图中显示的文件。

Not formatting the desired cells

有没有办法将数据框写入带有格式的Excel工作表?

1 个答案:

答案 0 :(得分:3)

不幸的是,如https://github.com/jmcnamara/XlsxWriter/issues/336所示,无法使用[{"foo" : "abc", "bar" : "def" },{"foo" : "xyz" },{"foo" : "ghi", "bar" : "jkl", "name" : "The Dude"}] 格式化datedatetime值。

您可以执行的操作是添加XlsxWriter以将数据框格式从df = df.astype(str) / date更改为datetime

string

输出:

enter image description here

请注意,如果您希望使用新格式覆盖标题,请添加到代码的开头:

df = pd.DataFrame(
    {
        'Date and time': [
            datetime(2015, 1, 1, 11, 30, 55),
            datetime(2015, 1, 2, 1,  20, 33),
            [ ... ]
        ],
        'Dates only': [
            date(2015, 2, 1),
            date(2015, 2, 2),
            [ ... ]
        ]
    }
)

df = df.astype(str)

writer = pd.ExcelWriter("pandas_datetime_format.xlsx",
                        engine='xlsxwriter',
                        [ ... ])

[ ... ]