Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to preserve macro buttons in Excel when adding data with Python
    text
    copied!<p>For a process I am maintaining, I have a script that creates a csv file and then I copy the csv file into an Excel workbook with buttons that activate macros. This process works just fine.</p> <p>I am trying to improve that process by writing a script that builds the workbook directly, thus eliminating a step. I thought the best way to do that was to create a template workbook where the first worksheet has the macro button. Then I would simply copy the template workbook, add in my data and save the new workbook under a new custom name. My test code is below:</p> <pre><code>import csv, os, sys, xlrd, xlwt, xlutils, shutil from copy import deepcopy from xlutils import save from xlutils.copy import copy templatefile = 'N:\Tools\Scripts-DEV\Testing_Template.xls' Destfile = 'N:\Tools\Scripts-DEV\Testing_Dest.xls' shutil.copy(templatefile,Destfile) # Works fine up to here. # If you look at the new file, it has the button that is in the template file. rb = xlrd.open_workbook(Destfile) rs = rb.sheet_by_index(0) wb = copy(rb) wb.get_sheet(0).write(3, 0, 'Due Date') wb.get_sheet(0).write(3, 1, 'Name') wb.get_sheet(0).write(3, 3, 'Category') wb.get_sheet(0).write(3, 4, 'Number') wb.save(Destfile) </code></pre> <p>Here is where the problem shows up. After you save, the macro button disappears. I've been looking for a couple days but I haven't (yet) found a way to save the updated Excel file without losing the macro button. </p> <p>I've been looking at <a href="https://stackoverflow.com/questions/3723793/preserving-styles-using-pythons-xlrd-xlwt-and-xlutils-copy">Preserving styles using python's xlrd,xlwt, and xlutils.copy</a> but that doesn't quite meet my needs as I'm trying to preserve a button, not a style.</p> <p>Does anyone know a way to do this? </p> <p>I'm about to start looking at alternatives to <code>xlutils, xlrd and xlwt</code> as well, but I thought I'd ask here first. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload