写一个pandasdf到Excel并保存到一个副本

我有一个pandas数据框,我想打开一个包含公式的现有Excel工作簿,将数据框复制到一组特定的列中(可以从列A到列H),并将其另存为具有不同名称的新文件。

这个想法是更新一个现有的模板,使用指定的一组列中的数据框填充它,然后用不同的名称保存一个Excel文件的副本。

任何想法?

我拥有的是:

import pandas from openpyxl import load_workbook book = load_workbook('Template.xlsx') writer = pandas.ExcelWriter('Template.xlsx', engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) df.to_excel(writer) writer.save() 

假设你很高兴复制到列A中,下面的代码应该可以工作。我没有办法从不同的列开始写入表单(不覆盖任何东西)。

下面的内容结合了@ MaxU的build议,在写入之前复制模板(刚刚在我自己的模板工作簿上丢失了几个小时的工作到pd.to_excel)

 import pandas as pd from openpyxl.utils.dataframe import dataframe_to_rows from shutil import copyfile template_file = 'Template.xlsx' # Has a header in row 1 already output_file = 'Result.xlsx' # What we are saving the template as # Copy Template.xlsx as Result.xlsx copyfile(template_file, output_file) # Read in the data to be pasted into the termplate df = pd.read_csv('my_data.csv') # Load the workbook and access the sheet we'll paste into wb = load_workbook(output_file) ws = wb.get_sheet_by_name('Existing Result Sheet') # Selecting a cell in the header row before writing makes append() # start writing to the following line ie row 2 ws['A1'] # Write each row of the DataFrame # In this case, I don't want to write the index (useless) or the header (already in the template) for r in dataframe_to_rows(df, index=False, header=False): ws.append(r) wb.save(output_file) 

尝试这个:

 df.to_excel(writer, startrow=10, startcol=1, index=False, engine='openpyxl') 

请注意startrowstartcol参数