2

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 .xlsx files from scratch and both can edit existing .xlsm files but I can't find any thing about actually creating a .xlsm file from scratch.

I've looked over the openpyxl documentation here and the xlsxwriter documentation here but I have not been able to find anything about how to create a .xlsm file from scratch. I can't even find anything about how to convert a .xlsx file to an .xlsm file.

The closest I have come is that you can use vba_extract.py which is included in xlsxwriter to extract a file named vbaProject.bin from an existing .xlsm file which you can then add to a .xlsx file and then you can save it as a .xlsm file, but I need to create a .xlsm file from scratch, not relying on having some file there to use to create it.

Is there anything out there with openpyxl, xlsxwriter or any other utility I can use with python 3.8.1 to create a .xlsm file from scratch without having to depend on having an existing .xlsm or a vbaProject.bin file? As always a correct, clearly explained answer will be marked as accepted and will be upvoted.

Gharbad The Weak
  • 1,541
  • 1
  • 17
  • 39

3 Answers3

2

Thanks to both Alexander Pushkarev and APhillips for helping out with this question. Going off of Alexander's post I was able to figure out a hack to get this to work. I'm not really proud of this, but it works.

Running Alexander's code I get this error:

Exception ignored in: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/zipfile.py", line 1819, in del self.close() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/zipfile.py", line 1836, in close self.fp.seek(self.start_dir) ValueError: I/O operation on closed file.

I played around with this and found out that if I took out keep_vba=True from the load_workbook function the code ran but I still got the error I noted above when trying to open the .xlsm file with Excel.

So, looking at the latest error I saw the last line says

I/O operation on closed file.

I looked at openpxyl documentation and tried opening the file without the keep_vba=True option before opening it with keep_vba=True and it worked.

So excuse this ugly code, but this will work to create a .xlsm file from scratch without depending on any existing files (copy and paste ready):

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
  • weird development, I don't know if it was due to a python version upgrade or something else, but now I am able to run the code above without the line that reads `wb1 = load_workbook('new_document.xlsm')` and it works just fine. – Gharbad The Weak Feb 16 '20 at 16:17
  • Hi, following works for me on OpenPyXL version 3.0.3 :`from openpyxl import Workbook, load_workbook filename = "New_macro_workbook.xlsm" wb = Workbook() wb.save(filename) wb2 = load_workbook(filename, keep_vba=True) wb2.save(filename)` – ConSod Jun 27 '20 at 18:45
  • What if I have to insert values into existing `.xlsm` excel, though I keep `keep_vba=True` I get the error that file is corrupted – Scope Oct 18 '20 at 21:11
  • BIG THANK YOU FOR THIS PIECE OF CODE! Solved one of my problems that I have been struggling for the last several days! – hkm Jul 18 '23 at 13:21
1

It appears as though an XLSM file is a zipped Excel file, containing macros, etc.

I was able to find a potential fix here using openpxyl:

import openpyxl as px
from openpyxl import load_workbook
import os
...
wbname='orig_fname.xlsm'
wb = load_workbook(filename=wbname, keep_vba=True)
...
wb.save('temp.xlsm')
os.rename('temp.xlsm', wbname)

Please let me know if it works for you.

Community
  • 1
  • 1
APhillips
  • 1,175
  • 9
  • 17
0

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')
Alexander Pushkarev
  • 1,075
  • 6
  • 19
  • 1
    that's correct, i can save a file with the `.xlsm` extension and it get's created just fine, but I get an error when I try to open that file that says something along the lines of the file extension isn't correct or the file is corrupted. I know that the `.xlsm` extension is valid because if i create a `.xlsm` file using excel on my mac, i am able to open it just fine. Thanks for the suggestion though. – Gharbad The Weak Jan 03 '20 at 21:17
  • Strange, I was able to open the document (I used LibreOffice, though) – Alexander Pushkarev Jan 03 '20 at 21:24
  • yeah, copied and pasted the code above, and the `.xlsm` file was created. again, however, when i tried to open the file, I get an error that says "Excel cannot open the file 'new_document.xlsm' because the file format or the file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file." – Gharbad The Weak Jan 03 '20 at 21:28
  • @GharbadTheWeak I guess I found the problem - please see updated answer – Alexander Pushkarev Jan 03 '20 at 21:31
  • i think this is close, but when i try to run the complete code example from above i get an this error: Exception ignored in: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/zipfile.py", line 1819, in __del__ self.close() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/zipfile.py", line 1836, in close self.fp.seek(self.start_dir) ValueError: I/O operation on closed file. – Gharbad The Weak Jan 03 '20 at 23:34
  • this is coming from the keep_vba=True part of the load_workbook statement. if i take out the keep_vba=True the code runs but i get the same error as before when trying to open the file – Gharbad The Weak Jan 03 '20 at 23:35
  • Thank you so much for your input on my question. Your code didn't work 100% for me but it definitely put me on the right track, I posted the answer I came up with based on your code. I didn't upvote your answer because it didn't work for me and I don't want to confuse anyone who looks at this but I thank you very much for your help! – Gharbad The Weak Jan 04 '20 at 00:12
  • @GharbadTheWeak Well done on finding the solution for the issue! You should mark your reply as accepted since it works – Alexander Pushkarev Jan 04 '20 at 12:14