简体   繁体   English

将pandas df写入Excel,并将其保存到副本中

[英]Write a pandas df into Excel and save it into a copy

I have a pandas dataframe and I want to open an existing excel workbook containing formulas, copying the dataframe in a specific set of columns (lets say from column A to column H) and save it as a new file with a different name. 我有一个pandas数据框,我想打开一个包含公式的现有excel工作簿,将数据框复制到一组特定的列中(比如说从A列到H列),然后将其另存为一个新文件。

The idea is to update an existing template, populate it with the dataframe in a specified set of column and then save a copy of the Excel file with a different name. 想法是更新现有模板,在指定的列集中使用数据框填充该模板,然后使用其他名称保存Excel文件的副本。

Any idea? 任何想法?

What I have is: 我所拥有的是:

  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()

The below should work, assuming that you are happy to copy into column A. I don't see a way to write into the sheet starting in a different column (without overwriting anything). 假设您很高兴将其复制到A列中,那么下面的方法应该起作用。我看不到从另一列开始写入工作表的方法(不覆盖任何内容)。

The below incorporates @MaxU's suggestion of copying the template sheet before writing to it (having just lost a few hours' work on my own template workbook to pd.to_excel) 下面结合了@MaxU的建议,即在写入模板表之前将其复制(刚刚在我自己的模板工作簿上花了几个小时的工作丢失到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 i.e. 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)

try this: 尝试这个:

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

Pay attention at startrow and startcol parameters 注意startrowstartcol参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM