0

我已经编写了一个程序,我正在尝试将结果导出到 excel 中。我在函数内部有这个(虽然我现在有点认为它应该在主函数之外)。

 minas=minas_ex.get()


data = pd.DataFrame(data =all_together)
data=data.transpose()
##book= load_workbook('FromPython.xlsx')
writer= pd.ExcelWriter('FromPython.xlsx',engine='openpyxl')
##writer.book = book
writer.sheets={ws.title: ws for ws in book.worksheets}
data.to_excel(writer,sheet_name=month,startrow=0,startcol=0,header=minas, index = False)

writer.save()

它似乎压倒了结果。我正在尝试将结果(all_together)打印到之前选择的月表中。但我希望他们追加而不是覆盖。在以前的版本中,我设法附加了结果,但似乎下一个保存的结果没有附加到下一行,它只是继续在转置上写入,例如:

我希望它显示:

item | price | tax | etc
something| 123| 132| etc
sth_else| 132| 231| etc

我忘了,我希望它选择要附加的工作表(这是通过程序前面的按钮给出的。)

4

1 回答 1

1

显然,事情并没有我想的那么简单。从https://medium.com/better-programming/using-python-pandas-with-excel-d5082102ca27#9cd6窃取

import pandas as pd
from openpyxl import load_workbook
# new dataframe with same columns
df = pd.DataFrame({'Name': ['E','F','G','H'],
                   'Age': [100,70,40,60]})
writer = pd.ExcelWriter('demo.xlsx', engine='openpyxl')
# try to open an existing workbook
writer.book = load_workbook('demo.xlsx')
# copy existing sheets
writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)
# read existing file
reader = pd.read_excel(r'demo.xlsx')
# write out the new sheet
df.to_excel(writer,index=False,header=False,startrow=len(reader)+1)

writer.close()

于 2020-06-09T16:59:49.227 回答