我正在使用 xlsxwriter 和 set_column 函数来格式化我的Excel输出中的列。
但是,应用于索引列(或多索引时的索引列)时,格式似乎会被忽略。
我找到了一个解决方法,到目前为止引入了一个带有 reset_index 的虚假索引,然后将 index = False 传递给to_excel函数,但接着是良好的合并功能多指数也将消失。
有什么想法吗?
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()
答案 0 :(得分:1)
大熊猫ExcelWriter
会覆盖索引列中的XlsxWriter
格式。
为防止这种情况,请将熊猫header_style
更改为None
header_style = {"font": {"bold": True},
"borders": {"top": "thin",
"right": "thin",
"bottom": "thin",
"left": "thin"},
"alignment": {"horizontal": "center",
"vertical": "top"}}
要这样做:
import pandas.io.formats.excel
pandas.io.formats.excel.header_style = None
另请参见
答案 1 :(得分:1)
据我了解, Pandas设置索引行的格式。有多种方法可以重置它,但是这些解决方案不是很可靠。实际格式化它也很困难。
以所需的格式写出索引列对我来说最合适:
import pandas as pd
# The data that we're feeding to ExcelWriter
df = pd.DataFrame(
{
"Col A": ["a", "a", "b", "b"],
"Col B": ["a", "b", "c", "d"],
"Col C": [1, 2, 3, 4],
}
)
# The Excel file we're creating
writer = pd.ExcelWriter("pandas_out.xlsx", engine="xlsxwriter")
df.to_excel(writer, sheet_name="Sheet1", index=False) # Prevents Pandas from outputting an index
# The variables we'll use to do our modifications
workbook = writer.book
worksheet = writer.sheets["Sheet1"]
worksheet.set_row(0, 30) # Set index row height to 30
# Find more info here: https://xlsxwriter.readthedocs.io/format.html#format-methods-and-format-properties
header_format = workbook.add_format(
{
"bold": True,
"valign": "vcenter",
"align": "center",
"bg_color": "#d6d6d6",
"border": True,
}
)
# Write the column headers with the defined format.
for col_num, value in enumerate(df.columns.values):
worksheet.write(0, col_num, value, header_format)
# Set format of data
format1 = workbook.add_format({"align": "center"})
worksheet.set_column('A:Z', 10, format1) # Width of cell
writer.save()
答案 2 :(得分:1)
要添加到 @Max 的答案中,这对 Pandas 1.1.5 有用:
import pandas.io.formats.excel
pandas.io.formats.excel.ExcelFormatter.header_style = None
答案 3 :(得分:0)
pandas/io/excel/_xlsxwriter.py
这适用于 1.1.5:
import numpy as np
import pandas as pd
from pandas.io.formats.excel import ExcelFormatter
from typing import Dict, Any
# from Config import TEMP_XL_FILE
TEMP_XL_FILE = 'headers.xlsx'
class CenteredFormatter(ExcelFormatter):
@property
def header_style(self) -> Dict[str, Any]:
d = dict(super().header_style)
d.setdefault('alignment', {})['horizontal'] = 'center'
d.setdefault('number_format', {})['format_code'] = '0%'
return d
def temp() -> None:
with pd.ExcelWriter(TEMP_XL_FILE, engine='xlsxwriter') as writer:
pdf = pd.DataFrame(np.random.randn(6, 4), columns=list('ABCD'))
pdf.set_index('A', drop=True, inplace=True)
formatter = CenteredFormatter(pdf)
formatter.write(writer, sheet_name='temp')
if __name__ == '__main__':
temp()