0

我的 python 代码中有多个列表,我想将这些列表复制到已经存在的 excel 文件中的不同列中。

    writer = pd.ExcelWriter('sample.xlsx')
    pd.DataFrame(timedata).to_excel(writer, 'timedata')
    writer.save()

这会将列表写入 excel,但它始终会覆盖 excel 中的数据,并且在此代码中未定义在多列中写入多个列表。

4

1 回答 1

0

Pandas 将 openpyxl 用于 xlsx 文件(在 pd 文档中提到)。通过检查 ExcelWriter 的文档,您可以看到这样的事情可能会奏效:

import pandas
from openpyxl import load_workbook

book = load_workbook('sample.xlsx')
writer = pandas.ExcelWriter('sample.xlsx', engine='openpyxl') 
writer.book = book

## ExcelWriter for some reason uses writer.sheets to access the sheet.
## If you leave it empty it will not know that sheet Main is already there
## and will create a new sheet.

writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

#data_filtered is a pd dataframe
data_filtered.to_excel(writer, "Main", cols=['col1', 'col2'])

writer.save()

如果你使用的是 0.24 之后的 pandas 版本,那么这个过程就更加简化了:

import pandas as pd

with pd.ExcelWriter('sample.xlsx', engine='openpyxl', mode='a') as writer: 
     data_filtered.to_excel(writer) 
于 2020-06-25T09:37:31.247 回答