user1070061
user1070061

Reputation: 503

How to preserve macro buttons in Excel when adding data with Python

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.

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:

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)

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.

I've been looking at Preserving styles using python's xlrd,xlwt, and xlutils.copy but that doesn't quite meet my needs as I'm trying to preserve a button, not a style.

Does anyone know a way to do this?

I'm about to start looking at alternatives to xlutils, xlrd and xlwt as well, but I thought I'd ask here first.

Upvotes: 2

Views: 2655

Answers (1)

Anthon
Anthon

Reputation: 76712

From you comment part C:\Python27\ I deduce that you are on Windows. In that case you are probably better off with using pywin32 and a template .xls or .xlsm file.

Open the file using os.startfile(filename) then connect using workbook = win32com.client.GetObject(filename). The resulting workbook can be filled with the data and written to a new file with `workbook.SaveAs(newfilename).

Anything you do not touch explicitly is preserved. Excel is, of course, somewhat better at that than xlrd, xlwt and xlutils.

Upvotes: 1

Related Questions