简体   繁体   中英

Issue with column names in XlsxWriter and Pandas

I am looking at automating a very small bit of my job that has to do with editing some files around, simple copy pasting in excel.I have been mildly successful in doing so in CSV and unformatted excel files. However the last file has to be formatted and I decided to uses XlsxWriter to do that. I am encountering an issue where the column names won't appropriately adjust to the left when I remove the index. On top of that some of the formatting is moving (column width) and other bits aren't (color, alignment, etc).

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()

Basic overview, data is an existing dataframe that I manipulate earlier and save as a csv mainly to keep track of the workflow, I have had no issues when exporting it as a csv and removing the index.

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

Rows and columns are zero indexed in XlsxWriter so you probably need col_num rather than col_num +1 when you write the header In your example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM