0

is there a way to create a new .XLSM file in python? (alternatively) Is there a way to create .XLSM file from a .XLS or .XLSX file within python?

from openpyxl import Workbook
wb = Workbook()
wb.save('myExcelFile.xlsm')

I tried the above but it creates a non-functioning/ corrupt file. Thanks in advance :)

Gharbad The Weak
  • 1,541
  • 1
  • 17
  • 39
ZAD
  • 51
  • 6

3 Answers3

2

I don't know anything about python or the openpyxl library but this snip might help, see the python comment. I found it in the openpyxl docs https://openpyxl.readthedocs.io/en/stable/tutorial.html#data-storage

It says must keep specify the attribute keep vba=true

enter image description here

1

Interestingly enough I had this exact same question earlier today. I figured out an answer (not pretty at all) but it works. Here is my post that details the answer and here is the code I came up with:

from openpyxl import Workbook
from openpyxl import load_workbook

wb = Workbook()
ws = wb.active
ws['A1'] = 42
ws.append([1, 2, 3])
wb.save('new_document.xlsm')
wb1 = load_workbook('new_document.xlsm')
wb2 = load_workbook('new_document.xlsm', keep_vba=True)
wb2.save('new_document.xlsm')
Gharbad The Weak
  • 1,541
  • 1
  • 17
  • 39
0

@Gharbad The Weak @Salvatore Allegra Thanks for the answers, appreciated :)

I found what I needed here

Tailoring it to what I needed:

import pandas as pd
filename = 'Name_here' + '.xlsx'
writer = pd.ExcelWriter(filename, engine='xlsxwriter')

filename_macro = 'Name_here' + '.xlsm' 
workbook = writer.book
workbook.filename = filename_macro
workbook.add_vba_project('vbaProject.bin')
writer.save()

(1) This creates a new .xlsm file

(2) It allows the attachment of a binary file containing a macro

ZAD
  • 51
  • 6