在pandas数据框中提供导出为ex​​cel的标题

时间:2017-10-17 07:53:14

标签: python excel pandas xlsxwriter

我有6个数据帧(名为af),我要导入到ms.excel,以便更容易阅读我想给每个数据帧添加标签,我尝试工作with cell notation,但我收到错误消息,这是我的代码:

writer = pd.ExcelWriter('Summary Data Request 8 weeks.xlsx')
a.to_excel(writer, sheet_name='Sheet1', startrow=1)
b.to_excel(writer, sheet_name='Sheet1', startcol=7)
c.to_excel(writer, sheet_name='Sheet1', startrow=11)
d.to_excel(writer, sheet_name='Sheet1', startrow=11, startcol=6)
e.to_excel(writer, sheet_name='Sheet1', startrow=21)
f.to_excel(writer, sheet_name='Sheet1', startrow=21, startcol=6)
writer.write('A1', 'Retail Kelontong')
writer.write('G1', 'Pulsa')
writer.write('A11', 'Minimarket')
writer.write('G11', 'Retail dengan barcode')
writer.write('A21', 'Retail dengan barcode 2')
writer.write('G21', 'Food and Beverage')
writer.save()

以下是错误消息:

AttributeError                            Traceback (most recent call last)
<ipython-input-30-2354b95670c9> in <module>()
      6 e.to_excel(writer, sheet_name='Sheet1', startrow=21)
      7 f.to_excel(writer, sheet_name='Sheet1', startrow=21, startcol=6) 
----> 8 writer.write('A1', 'Retail Kelontong')
      9 writer.write('G1', 'Pulsa')
     10 writer.write('A11', 'Minimarket')


AttributeError: '_XlsxWriter' object has no attribute 'write'

我仍然不知道自己做错了什么,我尝试将作者更改为Sheet1,错误信息为

name 'Sheet1' is not defined

我不知道该尝试什么

1 个答案:

答案 0 :(得分:2)

根据文档,您必须使用工作表的write方法,而不是编写者:

writer = pd.ExcelWriter('Summary Data Request 8 weeks.xlsx')
a.to_excel(writer, sheet_name='Sheet1', startrow=1)
b.to_excel(writer, sheet_name='Sheet1', startcol=7)
c.to_excel(writer, sheet_name='Sheet1', startrow=11)
d.to_excel(writer, sheet_name='Sheet1', startrow=11, startcol=6)
e.to_excel(writer, sheet_name='Sheet1', startrow=21)
f.to_excel(writer, sheet_name='Sheet1', startrow=21, startcol=6)
# Get sheet1
sheet1 = writer.sheets['Sheet1']
sheet1.write('A1', 'Retail Kelontong')
sheet1.write('G1', 'Pulsa')
sheet1.write('A11', 'Minimarket')
sheet1.write('G11', 'Retail dengan barcode')
sheet1.write('A21', 'Retail dengan barcode 2')
sheet1.write('G21', 'Food and Beverage')
writer.save()