chronossc/openpyxl

XLSM Macro Button Design

Closed this issue · 0 comments

Hi, when you have a button linked to a macro, when you save, the file comes with the macro but the button along with the link disappears.

After researching I came across with a solved problem. I adapted the original code to what I think it's the answer. Cheers

#Open the xlsm template for reading
workbook = openpyxl.load_workbook(filename='/home/xxx/templates/template.xlsm', read_only=False, keep_vba=True)
worksheet = workbook.get_sheet_by_name('Sheet1')

#Writing values
worksheet['C6'] = 1
worksheet['C7'] = 2
worksheet['C8'] = 3
worksheet['C9'] = 4

#Saving the output file as XLSX not XLSM (yet)
workbook.save(path_project + '/' + client + '.xlsx')

PAD = os.getcwd()

#Unzip the XLSM and XLSX to a temp folder. Did you know that?
with zipfile.ZipFile('/home/xxx/templates/template.xlsm', 'r') as z:
     z.extractall('./xlsm/')

with zipfile.ZipFile(path_project + '/' + client + '.xlsx', 'r') as z:
     z.extractall('./xlsx/')

#Copying the button style from the template to the output file.
copyfile('./xlsm/xl/drawings/drawing1.xml','./xlsx/xl/drawings/drawing1.xml')

#Zipping the whole thing as .zip
z = zipfile.ZipFile(path_project + '/' + client + '.zip', 'w')

#Directory change
os.chdir('./xlsx')

for root, dirs, files in os.walk('./'):
       for file in files:
            z.write(os.path.join(root, file))

z.close()

#clean and rename extension
os.chdir(PAD)
rmtree('./xlsm/')
rmtree('./xlsx/')
os.remove(path_project + '/' + client + '.xlsx')
os.rename(path_project + '/' + client + '.zip', path_project + '/' + client + '.xlsm')