问题
I'm using xlsxwriter and the set_column function that format the columns in my excel outputs.
However, formatting seems to be ignored when applied to the index column (or index columns in case of multi index).
I've found a workaround, so far is to introduce a fake index with reset_index then pass index=False to the to_excel function but then the nice merging feature of the multi index will be gone too.
Any ideas?
import pandas as pd
import numpy as np
from Config import TEMP_XL_FILE
def temp():
' temp'
pdf = pd.DataFrame(np.random.randn(6,4), columns=list('ABCD'))
pdf.set_index('A', drop=True, inplace=True)
writer = pd.ExcelWriter(TEMP_XL_FILE, engine='xlsxwriter')
pdf.to_excel(writer, 'temp')
workbook = writer.book
worksheet = writer.sheets['temp']
tempformat = workbook.add_format({'num_format': '0%', 'align': 'center'})
worksheet.set_column(-1, 3, None, tempformat)
writer.save()
if __name__ == '__main__':
temp()
回答1:
The pandas ExcelWriter
overwrites the XlsxWriter
formats in the index columns.
To prevent that, change the pandas header_style
to None
header_style = {"font": {"bold": True},
"borders": {"top": "thin",
"right": "thin",
"bottom": "thin",
"left": "thin"},
"alignment": {"horizontal": "center",
"vertical": "top"}}
To do that:
import pandas.io.formats.excel
pandas.io.formats.excel.header_style = None
See also
- xlsxwriter not applying format to header row of dataframe - Python Pandas
- Pandas raising: AttributeError: module 'pandas.core' has no attribute 'format'
来源:https://stackoverflow.com/questions/39892684/how-can-i-format-the-index-columns-with-xlsxwriter