简体   繁体   English

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

[英]How do I save a pandas df to excel sheet then format it?

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()

The above code was expected to generated a formatted excel sheet, with the columns B and B having blue background and other aspects specified in format_bc. 上面的代码应该生成一个格式化的excel表,其中列B和B具有蓝色背景和format_bc中指定的其他方面。 Instead I received a file shown in the image below. 相反,我收到了下图中显示的文件。

Not formatting the desired cells 不格式化所需的单元格

Is there a way to write a dataframe to an excel sheet with formatting? 有没有办法用格式化将数据帧写入Excel工作表?

Unfortunately as seen here https://github.com/jmcnamara/XlsxWriter/issues/336 , this is not possible to format date and datetime values with XlsxWriter . 不幸的是,如https://github.com/jmcnamara/XlsxWriter/issues/336所示 ,使用XlsxWriter格式化datedatetime值是XlsxWriter

What you could do instead is add df = df.astype(str) to change your dataframe formats from date / datetime to string . 你可以做的是添加df = df.astype(str)来将数据帧格式从date / datetime更改为string

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

[ ... ]

Outputs : 产出:

在此输入图像描述

Note that if you want the headers to be overwritten with the new format, add to the beginning of your code: 请注意,如果您希望使用新格式覆盖标题,请添加到代码的开头:

import pandas.io.formats.excel
pandas.io.formats.excel.header_style = None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从流式 excel 表解析到 python pandas df? - How to parse from from streaming excel sheet to python pandas df? 如何在Excel中将Excel Sheet保存为HTML? - How do I save Excel Sheet as HTML in Python? 导出到 excel 文件时,如何抑制 Pandas DF 中的科学记数法? - How do I suppress scientific notation in pandas DF when exporting to an excel file? 将pandas df写入Excel,并将其保存到副本中 - Write a pandas df into Excel and save it into a copy 如何保存我在Excel工作表上所做的更改? - How to save the changes I made on an Excel sheet? OpenPyxl 将 python df 保存到具有多张纸的 excel 文件中,但是当我打开文件时,它会在第一张纸上打开 - OpenPyxl save python df into excel file with multiple sheets but when I open the file it opens on the first sheet 如何使用 Pandas 在现有 excel 文件中保存新工作表? - How to save a new sheet in an existing excel file, using Pandas? 如何使用 python pandas 读取已打开的 excel 工作表 - How do I use python pandas to read an already opened excel sheet 如何确保Pandas上的“ read_excel”读取正确的图纸? - How do I ensure 'read_excel' on Pandas reads the correct sheet? 如何使用 pygsheets(带或不带 Pandas)将 Excel 工作表或 CSV 插入 Google 表格? - How do I insert an Excel sheet or CSV into Google Sheets using pygsheets (with or without Pandas)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM