写一个pandas.DataFrame
到 Excel 工作簿中.xlsx
格式很简单:
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
into a .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
其中将包含我的宏。但是,我更愿意自动执行此操作,而不需要额外的步骤。
The 的文档to_excel method表明这应该是可能的(参见engine
范围)。但是,我不明白如何启用此功能。
当我简单地将输出文件名更改为*.xlsm
, a .xlsx
文件被创建,它是named .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
,我可以再次打开它。
关于这部分的pandas文档:
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。
Using df.to_excel('test.xlsx', engine='openpyxl')
按照建议也没有解决问题。