用Python运行宏后如何保存Excel工作簿?

2024-05-23 13:30:51 发布

您现在位置:Python中文网/ 问答频道 /正文

python的代码可以工作,但是一旦运行,我仍然会从excel得到一个框,询问“希望将更改保存到工作簿”我的代码中似乎缺少的是添加一些可以在最后保存工作簿的内容。我在工作簿中使用RTD函数,这可能是弹出的原因。在

这是我使用的python代码。在

from __future__ import print_function
import unittest
import os.path
import win32com.client

class ExcelMacro(unittest.TestCase):
    def test_excel_macro(self):
        try:
            xlApp = win32com.client.DispatchEx('Excel.Application')
            xlsPath = os.path.expanduser('C:\Magic Samsung\Watch Samsung\Workbook.xlsm')
            wb = xlApp.Workbooks.Open(Filename=xlsPath)
            xlApp.Run('ArchiveMaster')
            wb.Save()
            xlApp.Quit()
            print("Macro ran successfully!")
        except:
            print("Error found while running the excel macro!")
            xlApp.Quit()
            if __name__ == "__main__":
            unittest.main()

Tags: path代码importclientosunittestexcelquit
1条回答
网友
1楼 · 发布于 2024-05-23 13:30:51

根据这个LinkxlOpenXMLWorkbookMacroEnabled是52。因此,在保存时,只需提供参数FileFormat=52,如下面的代码所示

class ExcelMacro(unittest.TestCase):
    def test_excel_macro(self):
        try:
            xlApp = win32com.client.DispatchEx('Excel.Application')
            xlapp.DisplayAlerts=False
            xlsPath = os.path.expanduser('C:\Magic Samsung\Watch Samsung\Workbook.xlsm')
            wb = xlApp.Workbooks.Open(Filename=xlsPath)
            xlApp.Run('ArchiveMaster')
            wb.SaveAs(Filename=path_here, FileFormat=52)
            xlApp.Quit()
            print("Macro ran successfully!")
        except:
            print("Error found while running the excel macro!")
            xlApp.Quit()
            if __name__ == "__main__":
            unittest.main()

注意:使用saveAs时会出现一个弹出窗口。这个SO questionThis So Post答案是这个问题

相关问题 更多 >