将数据框写入现有Excel工作表而不覆盖,并使用其他文件名保存

2024-09-30 16:38:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将数据帧写入现有的Excel工作表,而不进行覆盖,并使用Python使用另一个文件名保存它

import pandas as pd
import openpyxl

srcfile = openpyxl.load_workbook('C:\\Users\\kavitha.j\\Desktop\\Automation\\Report builder\\template.xlsx',read_only=False, keep_vba= True)*#to open the excel sheet and if it has macros*

df=pd.read_excel('C:\\Users\\kavitha.j\\Desktop\\Automation\\Report builder\\CVS Report Builder test.xlsx',sheet_name='Landing Page',skiprows=8)
df
sheetname = srcfile.get_sheet_by_name('Sheet1')#get sheetname from the file
sheetname.range('A9').value = df
sheetname.range('A9').options(pd.DataFrame, expand='table').value
srcfile.save('C:\\Users\\kavitha.j\\Desktop\\Automation\\Report builder\\finaltemplate.xlsm') #save it as a new file, the original file is untouched and here I am saving it as xlsm(m here denotes macros).

Tags: thereportdfasbuilderitusersfile