【问题标题】:Write to an existing .xlsm using pandas and XlsxWriter使用 pandas 和 XlsxWriter 写入现有的 .xlsm
【发布时间】:2019-08-04 09:37:46
【问题描述】:

我想将数据框写入已有内容的现有 .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 *

【问题讨论】:

    标签: python excel vba pandas


    【解决方案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)。

    【讨论】:

      猜你喜欢
      • 2017-03-30
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 1970-01-01
      • 2019-01-09
      相关资源
      最近更新 更多