我的代码有问题,不知道哪里出了问题。
我的问题的背景:
请帮助,非常感谢。请参阅下面的代码:
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)
答案 0 :(得分:0)
根据熊猫文档pandas documentation
在使用 ExcelWriter 对象时应该使用上下文管理器,特别是如果您想保存到多个工作表并且必须指定 mode for写入文件:
,如果只有一张纸,只需将 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)
`