【问题标题】:Write a pandas df into Excel and save it into a copy将 pandas df 写入 Excel 并保存到副本中
【发布时间】:2017-09-26 21:30:45
【问题描述】:

我有一个 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()

【问题讨论】:

  • 你的代码有什么问题?
  • 我建议先复制 'Template.xlsx' 文件,然后使用该副本,而不是“使用不同名称保存”
  • @MaxU 我无法设置起始列!

标签: python excel pandas


【解决方案1】:

假设您很乐意复制到 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)

【讨论】:

【解决方案2】:

试试这个:

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

注意startrowstartcol参数

【讨论】:

    猜你喜欢
    • 2017-03-30
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2010-12-21
    • 2018-02-07
    相关资源
    最近更新 更多