1 回答
TA贡献1963条经验 获得超6个赞
如您所见,格式继续到 AL、AM、AN、AO 等列。
这就是行格式在 Excel 中的工作方式。如果将其应用于一行,则所有单元格都会被格式化。
我可以以某种方式指定 A1:AK1 或类似的东西吗?
如果您只想格式化某些单元格,那么最好将格式仅应用于这些单元格。例如:
import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
header_data = ['EID', 'Notification', 'Test #']
header_format = workbook.add_format({'bold': True,
'bottom': 2,
'bg_color': '#F9DA04'})
for col_num, data in enumerate(header_data):
worksheet.write(0, col_num, data, header_format)
workbook.close()
输出:
如果重要的话,每个工作表都是使用 Pandas 的多个数据帧的 pd.concat() 的结果。
有关如何从数据帧格式化标头的示例,请参见 XlsxWriter文档中的此示例:
import pandas as pd
# Create a Pandas dataframe from the data.
df = pd.DataFrame({'Data1': [10, 20, 30, 20],
'Data2': [10, 20, 30, 20],
'Data3': [10, 20, 30, 20],
'Data4': [10, 20, 30, 20]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
# Turn off the default header and skip one row to allow us to insert a
# user defined header.
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False)
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Add a header format.
header_format = workbook.add_format({'bold': True,
'bottom': 2,
'bg_color': '#F9DA04'})
# Write the column headers with the defined format.
for col_num, value in enumerate(df.columns.values):
worksheet.write(0, col_num + 1, value, header_format)
# Close the Pandas Excel writer and output the Excel file.
writer.save()
输出:
添加回答
举报