Pandas:将数据框写入Excel(.xls)文件问题

时间:2015-12-31 17:56:08

标签: python pandas dataframe xls

我正在尝试将数据帧写入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中的列A仍然具有网格。

1 个答案:

答案 0 :(得分:2)

IIUC,set_column宽度你实际上写了df两次;正确的工作流程应该是以下(编辑:添加engine关键字):

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

这应该正确设置列宽。如果您不希望在输出中包含索引Time列,则应设置:

df.to_excel(writer,'Sheet1',index=False)

如果您之前已设置:

df.set_index = 'Time'

当您绘制完整的数据帧时,网格问题实际上仍然存在。我认为当前ExcelWriter对象不支持hide_gridlines()选项的索引,但我不知道它是否是错误。

编辑:感谢评论,这不是错误。