将pandas数据帧写入xlsm文件(启用了宏的Excel)

时间:2015-01-27 11:45:43

标签: python excel vba pandas

pandas.DataFrame格式将.xlsx写入Excel工作簿非常简​​单:

import pandas as pd
df = pd.DataFrame({'firstColumn' : [5, 2, 0, 10, 4], 'secondColumn' : [9, 8, 21, 3, 8]})
print(df)
df.to_excel('test.xlsx')

给出:

   firstColumn  secondColumn
0            5             9
1            2             8
2            0            21
3           10             3
4            4             8

和相应的Excel文件。

还有可能将DataFrame写入.xlsm Excel文件吗?这实际上与.xlsx大致相同,但可以在文件中存储VBA宏。我需要这个,因为我想在创建文件后插入并运行VBA宏。

但是,在常规xlsx文件上尝试此操作时,我会在弹出窗口中收到以下错误消息:

The following features cannot be saved in macro-free workbooks: VB project.
To save a file with these features, click No, and then choose a macro-enabled file type in the File Type list.
To continue saving as macro-free workbook, click Yes.

然后我可以手动选择将文件保存为.xlsm,其中包含我的宏。但是,如果没有额外的步骤,我宁愿自动执行此操作。

documentation for the to_excel method表明这应该是可行的(请参阅engine参数)。但是,我不明白如何启用它。

当我只是将输出文件名更改为*.xlsm时,会创建一个{em>名为 .xlsx的{​​{1}}文件。当我尝试打开它时,我得到了

.xlsm

如果我手动将扩展程序更改为Excel cannot open the file 'myFilename.xlsm' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file. ,我可以再次打开它。

关于this part of the pandas documentation

  

.xlsx:这包括对OpenPyxl 1.6.1的稳定支持,但不包括2.0.0,以及对OpenPyxl 2.0.0及更高版本的实验性支持。

我的openpyxl版本是1.8.6。更新到2.1.4并没有解决问题。也没有将Openpyxl从0.63更新为0.6.6。

建议使用XlsxWriter也无法解决问题。

1 个答案:

答案 0 :(得分:6)

Pandas要求工作簿名称以.xls.xlsx结尾。它使用扩展名来选择要使用的Excel引擎。

您可以传递临时名称,然后使用以下内容覆盖它:

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'
# !! Won't load in Excel !!

writer.save()

这将创建一个带有.xlsm扩展名的Excel文件。

但是,由于名为“扩展加固”的功能,Excel不会打开此文件,因为它知道它不包含宏而实际上不是xlsm文件。 (这是您在上面报告的Excel错误。)

通过从真实的xlsm文件中提取VbaProject.bin宏文件并将其插入新文件,您可以使用最新版本的XlsxWriter解决此问题:

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

writer.save()

有关详细信息,请参阅XlsxWriter文档的Working with VBA Macros部分。

相关问题