pandas 如何使用 XlsxWriter 将多种格式应用于一列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30564704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to apply multiple formats to one column with XlsxWriter
提问by metersk
In the below code I apply number formatting to each of the columns in my excel sheet. However, I can't seem to figure out to apply multiple formattings to a specific column, either the centering or the numbering end up being over written. Is it even possible to apply two types of formatting to one column?
在下面的代码中,我将数字格式应用于 Excel 工作表中的每一列。但是,我似乎无法弄清楚将多种格式应用于特定列,无论是居中还是编号最终都会被覆盖。甚至可以对一列应用两种格式吗?
def to_excel(video_report):
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
video_report.to_excel(writer, sheet_name='Sheet1', na_rep="-")
# Get the xlsxwriter objects from the dataframe writer object.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Add some cell formats.
integer = workbook.add_format({'num_format': '0'})
decimal = workbook.add_format({'num_format': '0.00'})
percentage = workbook.add_format({'num_format': '0.0%'})
center = workbook.add_format({'align': 'center'})
# APPLY CENTERING
worksheet.set_column('B:L', None, center)
# APPLY NUMBER FORMATTING
worksheet.set_column('B:B', 13, integer )
worksheet.set_column('C:C', 17, percentage )
worksheet.set_column('D:D', 19, percentage )
worksheet.set_column('E:E', 15, integer )
worksheet.set_column('F:F', 15, percentage )
worksheet.set_column('G:G', 15, decimal )
worksheet.set_column('H:H', 13, integer )
worksheet.set_column('I:I', 13, integer )
worksheet.set_column('J:J', 13, integer )
worksheet.set_column('K:K', 13, integer )
worksheet.set_column('L:L', 13, integer )
writer.save()
to_excel(video_report)
回答by jmcnamara
Is it even possible to apply two types of formatting to one column?
甚至可以对一列应用两种格式吗?
Yes. By adding the two or more properties to the format object that you are using. For example:
是的。通过将两个或多个属性添加到您正在使用的格式对象。例如:
integer = workbook.add_format({'num_format': '0', 'align': 'center'})
See the XlsxWriter docs on how to use formats.
回答by Clever Guy
While jmcnamara best answers the question, you can also define a new format object. Alternative example:
虽然 jmcnamara 最好地回答了这个问题,但您也可以定义一个新的格式对象。替代示例:
header = workbook.add_format({'align': 'center'})
header.set_bold()
header.set_italic()
header.set_underline()
worksheet.write(0, col_hdr, key, header)

