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

后端 未结 1 1709
青春惊慌失措
青春惊慌失措 2020-11-29 09:29

Writing a pandas.DataFrame into an Excel Workbook in the .xlsx format is as simple as:

import pandas as pd
df = pd.DataFrame({\'fir         


        
相关标签:
1条回答
  • 2020-11-29 10:21

    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.

    0 讨论(0)
提交回复
热议问题