我正在尝试将数据框架写入excel,并使单元格宽度(20)和试图隐藏网格线。到目前为止,我确实喜欢:

writer = ExcelWriter('output.xlsx')

df.to_excel(writer,'Sheet1')
writer.save()


worksheet = writer.sheets['Sheet1']

# Trying to set column width as 18
worksheet.set_column(0,3,18)
#the data frame has 2 columns and a row  - in xls it converts them to 3 columns

worksheet.hide_gridlines()
# I tried with option 2 - but this hides only the column grids, I mean the row(in data fram now became column A - it still has grid lines)

writer.save()

我的数据框看起来像:
                              Col1      Col2
  Time
   2011-01-01 01:00:00        4345        0.444

   2011-01-01 11:00:00        443         7.4

这条路不对吗?我看不到输出文件中的更改。我在这里做错了什么?有办法给我的行标题命名吗?
在这里。当试图隐藏网格线时。现在,excel中的行(在数据框['Time])中的列A仍然有网格。

最佳答案

IIUC,对于set_column宽度,您实际上要写两次df;正确的工作流应该是以下内容(EDIT:addengine关键字):

import pandas as pd

writer = pd.ExcelWriter('output.xlsx', engine='xlsxwriter')

df.to_excel(writer,'Sheet1')

worksheet = writer.sheets['Sheet1']

# Trying to set column width as 18
worksheet.set_column(0,3,18)
#the data frame has 2 columns and a row  - in xls it converts them to 3 columns

worksheet.hide_gridlines()
# I tried with option 2 - but this hides only the column grids, I mean the row(in data fram now became column A - it still has grid lines)

writer.save()

这应该正确设置列宽。如果不希望在输出中包含indexTime列,则应设置:
df.to_excel(writer,'Sheet1',index=False)

如果您以前设置过:
df.set_index = 'Time'

网格问题实际上在绘制完整数据帧时仍然存在。我认为当前的ExcelWriter对象不支持hide_gridlines()选项的索引,但我不知道它是否是一个bug。
编辑:感谢你的评论,这不是一个bug。

10-06 13:50
查看更多