使用Pandas和XlsxWriter写入现有的.xlsm

时间:2019-03-13 16:12:05

标签: python excel vba pandas

我想将数据帧写入到已经具有内容的现有.xlsm文件中。

Write pandas dataframe to xlsm file (Excel with Macros enabled)介绍了如何写入新文件,但我想编写将新工作表添加到现有.xlsm文件的方法。当我使用以下命令(如在问题中)时:

import pandas as pd

df = pd.DataFrame({'First' : [5, 2, 0, 10, 4], 
               'Second' : [9, 8, 21, 3, 8]})

writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')

df.to_excel(writer, sheet_name='Sheet1')

workbook  = writer.book
workbook.filename = 'test.xlsm'
workbook.add_vba_project('./vbaProject.bin')

df.to_excel(writer, sheet_name='Sheet1') #This is the df I'm trying to add to the sheet
writer.save()

它会覆盖原始内容,而现有的.xlsm文件仅具有新添加的工作表。

我不太清楚如何修改上面链接的问题中的代码以考虑现有文件。

谢谢

*我已经提取了此处描述的vbaProject.bin广告:https://xlsxwriter.readthedocs.io/working_with_macros.html *

1 个答案:

答案 0 :(得分:1)

使用此XlsxWriter解决方法时,我遇到了相同的问题。我认为您需要将现有的工作表复制/粘贴到writer.sheets中。解决问题的一种方法是添加

writer.sheets = {ws.title: ws for ws in writer.book.worksheets}

但是此语法不适用于engine ='xlsxwriter'

要将DataFrame添加到xlsm表中,我所做的只是:

import pandas
import openpyxl

writer = pandas.ExcelWriter(excel_file_path, engine='openpyxl')

writer.book = openpyxl.load_workbook(excel_file_path, keep_vba= True)
writer.sheets = {ws.title: ws for ws in writer.book.worksheets}

dataframe_to_insert.to_excel(writer, sheet_name= sheet_destination)

workbook = writer.book
workbook.filename = excel_file_path

writer.save()
writer.close()

似乎keep_vba= True为我完成了工作(Python 3.8.x)。