以.xlsx
格式将pandas.DataFrame
写入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 ^{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
,则可以再次打开它。
关于this part of the ^{
openpyxl
: This includes stable support for OpenPyxl 1.6.1 up to but not including 2.0.0, and experimental support for OpenPyxl 2.0.0 and later.`
我的Openpyxl
版本是1.8.6。升级到2.1.4并不能解决问题。也没有将XlsxWriter
从0.63更新到0.6.6。
按建议使用df.to_excel('test.xlsx', engine='openpyxl')
也不能解决问题。
Pandas要求工作簿名称以
.xls
或.xlsx
结尾。它使用扩展来选择要使用的Excel引擎。您可以传递一个临时名称,然后用如下内容覆盖它:
这将创建一个扩展名为
.xlsm
的Excel文件。但是,由于名为“扩展强化”的功能,Excel不会打开此文件,因为它知道它不包含宏并且实际上不是
xlsm
文件。(这是上面报告的Excel错误。)通过从真实的xlsm文件中提取
VbaProject.bin
宏文件并将其插入新文件,可以使用XlsxWriter的最新版本解决此问题:有关详细信息,请参阅XlsxWriter文档的Working with VBA Macros部分。
相关问题 更多 >
编程相关推荐