Writing a pandas.DataFrame
into an Excel Workbook in the .xlsx
format is as simple as:
import pandas as pd
df = pd.DataFrame({\'fir
Pandas requires that a workbook name ends in .xls
or .xlsx
. It uses the extension to choose which Excel engine to use.
You could pass a temp name and then overwrite it with something like this:
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()
This will create an Excel file with the a .xlsm
extension.
However, due to a feature called "extension hardening" Excel won't open this file since it knows that it doesn't contain a macro and isn't actually an xlsm
file. (That is the Excel error that you report above.)
You can workaround this with recent versions of XlsxWriter by extracting the VbaProject.bin
macro file from a real xlsm file and inserting it into the new file:
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()
See the Working with VBA Macros section of the XlsxWriter docs for more information.