簡體   English   中英

將 Pandas 數據幀寫入 xlsm 文件(啟用宏的 Excel)

[英]Write pandas dataframe to xlsm file (Excel with Macros enabled)

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 ,其中將包含我的宏。 但是,我更願意在沒有額外步驟的情況下自動執行此操作。

to_excel方法文檔表明這應該是可能的(請參閱engine參數)。 但是,我不明白如何啟用它。

當我簡單地將輸出文件名更改為*.xlsm ,會創建一個名為.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 ,我可以再次打開它。

關於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。

按照建議使用df.to_excel('test.xlsx', engine='openpyxl')也沒有解決問題。

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 錯誤。)

您可以使用最新版本的 XlsxWriter 解決此問題,方法是從真實的 xlsm 文件中提取VbaProject.bin宏文件並將其插入到新文件中:

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 宏部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM