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
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')