【问题标题】:Pandas: Writing data frame to Excel (.xls) file issuePandas:将数据框写入 Excel (.xls) 文件问题
【发布时间】:2016-01-02 05:31:20
【问题描述】:

我正在尝试将数据框写入 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仍然有网格。

【问题讨论】:

  • 你的意思是“有没有办法给我的行命名?”索引默认包含在写入的数据中,索引有效地命名了所有的行.
  • 我的意思是行标题。对不起!
  • 您应该至少包含一个数据框样本以重现您的问题。
  • @FabioLamanna 请看更新一

标签: python pandas dataframe xls


【解决方案1】:

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() 选项的索引,但我不知道这是否是一个错误。

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

【讨论】:

  • 关于最后一段,这不是错误。 XlsxWriter 隐藏了网格线,可以通过进入打印预览来验证。索引周围可见的线条是 Pandas 默认添加的边框(不是网格线)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2021-09-06
  • 1970-01-01
  • 2017-09-18
相关资源
最近更新 更多