【问题标题】:Python (openpyxl) : Put data from one excel file to another (template file) & save it with another name while retaining the templatePython(openpyxl):将数据从一个excel文件放入另一个(模板文件)并在保留模板的同时用另一个名称保存
【发布时间】:2018-04-02 11:58:17
【问题描述】:

我有一个名为 template.xlsx模板 excel 文件,其中包含许多工作表。我想将单独的.csv 文件中的数据复制到template.xlsx 的第一张表中(命名为data)并将新文件另存为result.xlsx 同时保留原始模板文件。

我想从template.xlsxdata工作表的第二行开始粘贴数据

这是我目前开发的代码

import pandas as pd
from openpyxl.utils.dataframe import dataframe_to_rows
import openpyxl
from shutil import copyfile

template_file = 'template.xlsx' # Has a header in row 1 already which needs to be skipped while pasting data but it should be there in the output file
output_file = 'result.xlsx' 

copyfile(template_file, output_file)
df = pd.read_csv('input_file.csv') #The file which is to be pasted in the template

wb = openpyxl.load_workbook(output_file)
ws = wb.get_sheet_by_name('data') #Getting the sheet named as 'data'

for r in dataframe_to_rows(df, index=False, header=False):
   ws.append(r)

 wb.save(output_file)

我无法获得所需的输出

左边是模板文件(多了一行),右边是输入文件(要复制到模板的数据),如下所示

【问题讨论】:

    标签: python excel python-3.x openpyxl shutil


    【解决方案1】:

    实际上不需要使用 shutil 模块,因为您可以使用 openpyxl.load_workbook 加载模板,然后以不同的名称保存。

    另外,ws.append(r) 在你的 for 循环中将附加到从 template.xlsx 中获取的现有数据中,听起来你只想保留标题。

    我在下面提供了一个完全可重现的示例,该示例创建了“template.xlsx”用于演示目的。然后它加载“template.xlsx”,向其中添加新数据并保存为 result.xlsx。

    from openpyxl import Workbook
    from openpyxl import load_workbook
    from openpyxl.utils.dataframe import dataframe_to_rows
    from openpyxl.chart import PieChart, Reference, Series
    import pandas as pd
    
    template_file = 'template.xlsx'
    output_file = 'result.xlsx'
    
    #This part creates a workbook called template.xlsx with a sheet called 'data' and sheet called 'second_sheet'
    writer = pd.ExcelWriter('template.xlsx', engine='openpyxl') 
    wb  = writer.book
    df = pd.DataFrame({'Pie': ["Cream", "Cherry", "Banoffee", "Apple"],
                      'Sold': [2, 2, 1, 4]})
    
    df.to_excel(writer, index=False, sheet_name='data', startrow=1)
    ws = writer.sheets['data']
    ws['A1'] = 1
    ws['B1'] = 2
    
    ch = PieChart()
    labels = Reference(ws, min_col=1, min_row=3, max_row=6)
    data = Reference(ws, min_col=2, min_row=3, max_row=6)
    ch.series = (Series(data),)
    ch.title = "Pies sold"
    ws.add_chart(ch, "D2")
    
    ws = wb.create_sheet("Second_sheet")
    ws['A1'] = 'This Sheet will not be overwitten'
    
    wb.save(template_file)
    
    #Now we load workbook called template.xlsx modify the 'data' sheet and save under a new name
    #template.xlsx has not been modified
    
    df_new = pd.DataFrame({'different_name': ["Blueberry", "Pumpkin", "Mushroom", "Turnip"],
                      'different_numbers': [4, 6, 2, 1]})
    
    wb = load_workbook(template_file)
    
    ws = wb.get_sheet_by_name('data') #Getting the sheet named as 'data'
    
    rows = dataframe_to_rows(df_new, index=False, header=False)
    
    for r_idx, row in enumerate(rows, 1):
        for c_idx, value in enumerate(row, 1):
             ws.cell(row=r_idx+2, column=c_idx, value=value)
    
    wb.save(output_file)
    

    预期输出:

    【讨论】:

    • 我的模板文件(我想保留)中有一个标题(额外的行),但我想从第二行开始粘贴我的数据(来自 .csv 文件)。我已经用图片编辑了我的问题,以便更容易理解我的文件的样子。此外,this will give some insight
    • 根据您的评论进行了一些更改。唯一重要的变化是我在创建 result.xlsx 时将所有内容都向下移动了一行。所以ws.cell(row=r_idx+1....改成了ws.cell(row=r_idx+2....
    • 正在粘贴数据,但未生成基于新粘贴数据的图表和图形。模块不支持这个功能吗?
    • 模块确实支持这个功能。我已经更新了答案以在其中放置图表。您可能希望通过在命令行$ python -m pip install --upgrade openpyxl 中执行此操作来确保您使用的是最新版本
    • 谢谢。但是,我的图表在另一张表中(假设您的情况是 Second_sheet)。其次,我在windows上
    猜你喜欢
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2020-01-03
    • 2012-06-14
    • 2018-03-23
    • 2018-09-28
    相关资源
    最近更新 更多