熊猫 to_excel 没有数据

时间:2021-02-24 10:41:13

标签: python pandas pandas.excelwriter

我的代码有问题,不知道哪里出了问题。

我的问题的背景:

  • 我使用 Pandas 从网络上查询股价数据(多只股票)。
  • 然后,将数据导出到现有的 excel 文件中。
  • 数据框确实有数据。
  • 但是,文件完成后没有数据(我同时使用 ExcelWriter 和 itertuples,但没有成功)。

请帮助,非常感谢。请参阅下面的代码:

wb = op.load_workbook(file_location)
full_path = os.path.abspath(file_location)

for stock in stocklist:
   if stock in avail_sheets:
      #Delete existing tabs for having fresh start.
      wb.remove(wb[stock])   

   wb.create_sheet(stock)
   symbol = stock+".AX"  #to specify ASX stock
   url = get_url(symbol, start_date, end_date)

   stock_data = pd.read_csv(url)
   writer = pd.ExcelWriter(full_path)
   stock_data.to_excel(writer, sheet_name =stock ,index = False, header = True)
   writer.save()

   # current_sheet = wb[stock]
   # for row in stock_data.itertuples(index=False):
   #     current_sheet.append(row)

wb.save(file_location) 

1 个答案:

答案 0 :(得分:0)

根据熊猫文档pandas documentation

在使用 ExcelWriter 对象时应该使用上下文管理器,特别是如果您想保存到多个工作表并且必须指定 mode for写入文件:

  1. 'a' = 追加。
  2. 'r' = 已读。
  3. 'w' = 写。

,如果只有一张纸,只需将 output.xlsx 文件传递​​给 .to_excel() 方法并指定工作表名称。

`
 # for single sheet
 stock_data.to_excel('output.xlsx', sheet_name=stock, index=False, header=True)

 # for multiple sheets or even single sheet
 with pd.ExcelWriter('output.xlsx', mode='a') as writer:
      stock_data.to_excel(writer, sheet_name=stock, index=False, header=True)
`