is there any way to create a .xlsm file from scratch in python?

后端 未结 3 884
感动是毒
感动是毒 2021-01-22 16:35

I am using python 3.8.1 on a mac and am trying to create a .xlsm file from scratch. I have looked at openpyxl and xlsxwriter, both of them are able to create

3条回答
  •  时光取名叫无心
    2021-01-22 17:16

    To the best of my knowledge, xlsm format is essentially the same as xlsx, with the only difference that it can contain macroses (see https://wiki.fileformat.com/spreadsheet/xlsm/ for instance).

    So, you can use openpyxl (https://openpyxl.readthedocs.io/en/stable/), and you don't need to do anything else other than saving your xlsx file with the xlsm extension (code is taken from the official doc and changed slightly):

    from openpyxl import Workbook
    wb = Workbook()
    ws = wb.active
    ws['A1'] = 42
    ws.append([1, 2, 3])
    wb.save('new_document.xlsm')
    

    However, there's a strange behaviour in openpyxl which is not documented properly, so to make file actually openable in the Excel you will also need:

    wb = load_workbook('new_document.xltm', keep_vba=True)
    wb.save('new_document.xlsm')
    

    There's a little bit of explanation for this here: https://openpyxl.readthedocs.io/en/stable/tutorial.html#saving-as-a-stream

    So the complete code:

    from openpyxl import Workbook
    wb = Workbook()
    ws = wb.active
    ws['A1'] = 42
    ws.append([1, 2, 3])
    wb.save('new_document.xlsm')
    # and the workaround
    wb = load_workbook('new_document.xltm', keep_vba=True)
    wb.save('new_document.xlsm')
    

提交回复
热议问题