XlsxWriter 和 Pandas 中的列名问题

Issue with column names in XlsxWriter and Pandas

我正在考虑将我的一小部分工作自动化,这些工作与编辑一些文件有关,excel.I 中的简单复制粘贴在 CSV 和未格式化的 [=26] 中取得了一定的成功=] 文件。然而,最后一个文件必须格式化,我决定使用 XlsxWriter 来做到这一点。我遇到了一个问题,即当我删除索引时,列名无法适当地向左调整。最重要的是,一些格式正在移动(列宽)而其他位则没有(颜色、对齐方式等)。

data_cols = ['Date', 'ID', 'Latitude', 'Longitude', 'Snow Accumulation at Customer Facility (inches)', 'Season Accumulation of Snow (inches)', 'Nearest Human Observed Snow Accumulation (inches)','Distance between snow observation site and customer facility (miles)','24 hr Maximum wind speed (mph)','24 hr Min. Temp. (degrees F)','Sleet or Freezing Rain (1=Yes; 0=No)']

data.columns = data_cols

writer = pd.ExcelWriter('C:/Users/csayre/Desktop/snowexpress_testbed/' + 'snowexpress_' + day.strftime("%m%d%y") + '_dentco.xlsx', engine = 'xlsxwriter')

data.to_excel(writer, sheet_name='Sheet1', index=False)

workbook  = writer.book
worksheet = writer.sheets['Sheet1']

header_format = workbook.add_format({
    'bold': False,
    'font_name': 'Arial',
    'font_size': 10,
    'text_wrap': True,
    'center_across': True,
    'valign': 'bottom',
    'fg_color': '#cdffff',
    'border': 1})

for col_num, value in enumerate(data.columns.values):
    worksheet.write(0, col_num + 1, value, header_format)


worksheet.set_column(0, 0, 14.43)
worksheet.set_column(1, 1, 18.86)
worksheet.set_column(2, 2, 8.71)
worksheet.set_column(3, 3, 10.43)
worksheet.set_column(4, 7, 11.57)
worksheet.set_column(8, 8, 12)
worksheet.set_column(9, 9, 9.57)
worksheet.set_column(10, 10, 9.57)

writer.save()

基本概述,数据是我之前操作并保存为 csv 的现有数据框,主要是为了跟踪工作流程,将其导出为 csv 并删除索引时我没有遇到任何问题。

This is what I am trying to produce

This is what this code produces with "index=false"

This is what it looks like with the index

行和列在 XlsxWriter 中的索引为零,因此您在编写 header 时可能需要 col_num 而不是 col_num +1 在您的示例中:

for col_num, value in enumerate(data.columns.values):
    worksheet.write(0, col_num, value, header_format)