[英]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
格式化date
和datetime
值是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.