熊猫:将数据帧写入Excel (.xls) 文件问题

2024-10-01 00:22:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将数据帧写入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()

我的数据框看起来像:

^{pr2}$

这条路错了吗?我在输出文件中看不到更改。我做错什么了?有没有办法命名我的行标题?在

这里。当试图隐藏网格线时。行(在数据框['Time])中,现在excel中的A列仍然有网格。在


Tags: columnstheto数据datasavecolumnexcel
1条回答
网友
1楼 · 发布于 2024-10-01 00:22:45

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

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

^{pr2}$

如果您以前设置过:

df.set_index = 'Time'

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

编辑:多亏了评论,这不是一个bug。在

相关问题 更多 >