【发布时间】:2018-04-02 11:58:17
【问题描述】:
我有一个名为 template.xlsx 的 模板 excel 文件,其中包含许多工作表。我想将单独的.csv 文件中的数据复制到template.xlsx 的第一张表中(命名为data)并将新文件另存为result.xlsx 同时保留原始模板文件。
我想从template.xlsx的data工作表的第二行开始粘贴数据
这是我目前开发的代码
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