【发布时间】:2015-03-26 00:33:56
【问题描述】:
以.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 to_excel method 表明这应该是可能的(参见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 pandas documentation:
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')也没有解决问题。
【问题讨论】:
-
如果您只是将文件名更改为
'test.xlsm'会发生什么?根据ExcelWritersource,engine“默认为io.excel.<extension>.writer”。另见pandas.pydata.org/pandas-docs/stable/… -
哦,是的,我忘了提...这会创建一个名为
xlsm的xlsx文件。当我尝试打开它时,我得到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,我可以再次打开它。 -
请您编辑问题以包含此信息和任何其他相关信息。您是否尝试过指定
engine='openpyxl'? -
不,没有其他错误 - 命名文件
xlsm时,我得到一个扩展名错误的xlsx文件。只需将文件命名为xlsm并且 pandas 会选择正确的引擎,它对您有用吗?如果不是,那么我猜熊猫的文档在这方面有点过于简化了,尤其是关于 jmcnamara 的(更复杂的)建议,它起到了作用。 -
我没有在此处安装
pandas,我只是想鼓励您提供所有适当的故障排除信息。不过,很高兴您找到了有效的答案。