简体   繁体   English

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

[英]Write to an existing .xlsm using pandas and XlsxWriter

I would like to write a dataframe to an existing .xlsm file which already has content.我想将数据帧写入已有内容的现有 .xlsm 文件。

Write pandas dataframe to xlsm file (Excel with Macros enabled) describes how to write to a new file but I want to write to add a new sheet to an existing .xlsm file. Write pandas dataframe to xlsm file (Excel with Macros enabled)描述了如何写入新文件,但我想写入以将新工作表添加到现有的 .xlsm 文件。 When I use the following (as in the question):当我使用以下内容时(如问题所示):

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()

it overwrites the original content and the existing .xlsm file only has the newly added sheet.它会覆盖原始内容,现有的 .xlsm 文件只有新添加的工作表。

I can't quite figure out how to amend the code in the linked question above to consider an existing file.我不太清楚如何修改上面链接问题中的代码以考虑现有文件。

Thanks谢谢

*I have extracted the vbaProject.bin ad described here: https://xlsxwriter.readthedocs.io/working_with_macros.html * *我已经提取了此处描述的 vbaProject.bin 广告: https : //xlsxwriter.readthedocs.io/working_with_macros.html *

I had the same issue using this XlsxWriter workaround.我在使用这个 XlsxWriter 解决方法时遇到了同样的问题。 I think you would need to copy/paste already existing sheets into writer.sheets.我认为您需要将现有的工作表复制/粘贴到 writer.sheets 中。 Maybe one way to fix it is to add a line like也许修复它的一种方法是添加一行

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

but this syntax does not work with engine = 'xlsxwriter'但此语法不适用于 engine = 'xlsxwriter'

To add a DataFrame to an xlsm sheet what I did is simply :要将 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()

It seems keep_vba= True is doing the job for me (Python 3.8.x).似乎keep_vba= True正在为我做这项工作(Python 3.8.x)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM