将熊猫数据框写入xlsm文件(启用了宏的Excel)
pandas.DataFrame
用以下.xlsx
格式将a写入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
包含宏的文件。但是,我希望自动执行此操作而无需执行额外的步骤。
该方法的文档to_excel
建议应该可行(请参阅engine
参数)。但是,我不知道如何启用此功能。
当我简单地将输出文件名更改为时*.xlsm
,将.xlsx
创建一个 名为 的文件.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.
如果我将扩展名手动更改为.xlsx
,则可以再次打开它。
openpyxl
:这包括对OpenPyxl 1.6.1(直到但不包括2.0.0)的稳定支持,以及对OpenPyxl
2.0.0和更高版本的实验性支持。
我的版本Openpyxl
是1.8.6。更新到2.1.4并不能解决问题。XlsxWriter
从0.63更新到0.6.6都没有。
df.to_excel('test.xlsx', engine='openpyxl')
按建议使用也不能解决问题。
-
熊猫要求工作簿名称以
.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错误。)您可以通过
VbaProject.bin
从实际的xlsm文件中提取宏文件并将其插入新文件中来解决最新版本的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文档的“使用VBA宏”部分。