Skip to main content
 首页 » 编程设计

python之使用 Python 添加数据时如何在 Excel 中保留宏按钮

2025年05月04日9zhenyulu

对于我正在维护的流程,我有一个创建 csv 文件的脚本,然后我将 csv 文件复制到带有激活宏的按钮的 Excel 工作簿中。这个过程工作得很好。

我正在尝试通过编写一个直接构建工作簿的脚本来改进该过程,从而消除一个步骤。我认为最好的方法是创建一个模板工作簿,其中第一个工作表有宏按钮。然后我会简单地复制模板工作簿,添加我的数据并以新的自定义名称保存新工作簿。我的测试代码如下:

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) 

这就是问题所在。保存后,宏按钮消失。我一直在寻找几天,但我(还)没有找到一种方法来保存更新的 Excel 文件而不丢失宏按钮。

我一直在看Preserving styles using python's xlrd,xlwt, and xlutils.copy但这并不能完全满足我的需求,因为我试图保留一个按钮,而不是一种样式。

有没有人知道如何做到这一点?

我也将开始寻找 xlutils、xlrd 和 xlwt 的替代品,但我想我应该先在这里问一下。

请您参考如下方法:

从你的评论部分 C:\Python27\ 我推断你在 Windows 上。在那种情况下,您最好使用 pywin32和模板 .xls 或 .xlsm 文件。

使用 os.startfile(filename) 打开文件,然后使用 workbook = win32com.client.GetObject(filename) 连接。可以用数据填充生成的工作簿,并使用 `workbook.SaveAs(newfilename) 将其写入新文件。

任何你没有明确触摸的东西都会被保留。当然,Excel 在这方面比 xlrd、xlwt 和 xlutils 要好一些。