实际上不需要使用shutil模块,因为您可以使用openpyxl.load_工作簿加载模板,然后用其他名称保存。在
此外,for循环中的ws.append(r)将附加到现有的数据中模板.xlsx,听起来你只想保留标题。在
我在下面提供了一个完全可复制的例子模板.xlsx“为了演示目的。然后装载模板.xlsx'添加新数据并另存为结果.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,