簡體   English   中英

將pandas df寫入Excel,並將其保存到副本中

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

我有一個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的建議,即在寫入模板表之前將其復制(剛剛在我自己的模板工作簿上花了幾個小時的工作丟失到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)

嘗試這個:

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

注意startrowstartcol參數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM