Skip to main content
 首页 » 编程设计

python之任务计划程序不会运行 python 脚本 (pywin32) 来打开 Excel。如何从 Pywin32 获取更多信息

2025年05月04日13yyy_WW

我有一个在 Windows Server 2008 上运行的 Python 脚本。它打开一个电子表格并向电子表格添加一个筛选行,关闭它然后将其压缩。主电子表格是使用 xlwt 创建的。我只使用 Pywin32,因为用户想要添加一个筛选行。

当手动执行时(即直接通过 Windows 资源管理器或命令行)它有效。但是,当通过 Task Schduler 手动触发脚本或让它在所需时间触发时,它不起作用。

“运行身份”用户是管理员。我已经检查以确保它以最高权限运行。

我通过将输出管道输出到日志文件来捕获错误消息。回溯显示:

File "C:\www\..\main\management\commands\excel_writer.py", line 183, in add_filter_control 
    xl.Workbooks.Open(file_path) 
File "<COMObject <unknown>>", line 8, in Open 
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Office Excel', u'Die Open-Methode des Workbooks-Objektes konnte nicht ausgef\xfchrt werden.', u'C:\\Program Files\\Microsoft Office\\OFFICE11\\1031\\xlmain11.chm', 0, -2146827284), None) 

好的...这是德文的,但基本上是说“无法执行工作簿打开方法”。

但是,我不知道为什么。有没有人对如何找出原因有任何提示?

干杯

行政法官

这里是一些代码和设置:

电子表格创建代码

... 
w = xlwt.Workbook('UTF-8') 
    worksheets = {}  
 
    data_formatting_dict = construct_data_formatting() 
 
    for sheetref, sheetname, datasource, dataformat_ref in sheetlist: 
        worksheets[sheetref] = w.add_sheet(sheetname) 
        fetch_row_heights(sheetref, dataformat_ref) 
        xls_set_columnwidth(sheetref, dataformat_ref) 
        xls_set_main_titles(sheetref, sheetname, dataformat_ref) 
        xls_set_titles(sheetref, sheetname, dataformat_ref) 
        xls_insert_filter_row(sheetref, dataformat_ref) 
        xls_freeze_panes(sheetref, dataformat_ref) 
        xls_write_lines(sheetref,dataformat_ref,datasource,pre_title_rows+title_rows+post_title_rows) 
 
    filename = fileroot + ".xls" 
    archive = fileroot + ".zip" 
    filepath = os.getcwd() + "\\" + filename 
    w.save(filepath) 
 
    add_filter_control(filepath)  << This is where the filter code is called. 
 
    ziparchive(filename, archive)     
    full_archive_ref = save_to_folder + archive 
    shutil.copy(archive, full_archive_ref) 
 
    os.remove(filename) 
    os.remove(archive) 
... 

add_filter_control

def add_filter_control(file_path): 
    try:  
        from win32com.client import Dispatch 
    except: 
        return 
 
    xl = Dispatch("Excel.Application")  
    xl.Workbooks.Open(file_path)  
    for id, sheetname, source, formatref in sheetlist: 
        cellref = format_params[formatref]['filter_range'] 
        if cellref is not None: 
            xl.ActiveWorkbook.Worksheets(sheetname).Range(cellref).AutoFilter(1) 
    xl.ActiveWorkbook.Close(SaveChanges=1) # 1 is True, 0 is False 
    xl.quit() 

任务计划程序设置

<?xml version="1.0" encoding="UTF-16"?> 
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> 
  <RegistrationInfo> 
    <Date>2010-07-23T21:25:09.4036437</Date> 
    <Author>WIN-1CW6Q4GAAAM\Administrator</Author> 
    <Description>Refreshes the temp tables in the database and generates the summary report spreadsheet.</Description> 
  </RegistrationInfo> 
  <Triggers> 
    <CalendarTrigger> 
      <StartBoundary>2010-07-23T05:00:00</StartBoundary> 
      <ExecutionTimeLimit>PT1H</ExecutionTimeLimit> 
      <Enabled>true</Enabled> 
      <ScheduleByDay> 
        <DaysInterval>1</DaysInterval> 
      </ScheduleByDay> 
    </CalendarTrigger> 
  </Triggers> 
  <Principals> 
    <Principal id="Author"> 
      <UserId>WIN-1CW6Q4GAAAM\Administrator</UserId> 
      <LogonType>Password</LogonType> 
      <RunLevel>HighestAvailable</RunLevel> 
    </Principal> 
  </Principals> 
  <Settings> 
    <IdleSettings> 
      <Duration>PT10M</Duration> 
      <WaitTimeout>PT1H</WaitTimeout> 
      <StopOnIdleEnd>true</StopOnIdleEnd> 
      <RestartOnIdle>false</RestartOnIdle> 
    </IdleSettings> 
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> 
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries> 
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries> 
    <AllowHardTerminate>true</AllowHardTerminate> 
    <StartWhenAvailable>true</StartWhenAvailable> 
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> 
    <AllowStartOnDemand>true</AllowStartOnDemand> 
    <Enabled>true</Enabled> 
    <Hidden>false</Hidden> 
    <RunOnlyIfIdle>false</RunOnlyIfIdle> 
    <WakeToRun>false</WakeToRun> 
    <ExecutionTimeLimit>PT1H</ExecutionTimeLimit> 
    <Priority>7</Priority> 
  </Settings> 
  <Actions Context="Author"> 
    <Exec> 
      <Command>run_reports.bat</Command> 
      <WorkingDirectory>C:\www\my_site\mysite\</WorkingDirectory> 
    </Exec> 
  </Actions> 
</Task> 

请您参考如下方法:

经过几天的搜索,我找到了以下解决方案(完整线程可以在 http://social.msdn.microsoft.com/Forums/en/innovateonoffice/thread/b81a3c4e-62db-488b-af06-44421818ef91 找到)

在 systemprofile 文件夹中似乎需要 Desktop 文件夹才能通过 Excel 打开文件。您需要创建以下文件夹之一:

Windows 2008 服务器 x64

C:\Windows\SysWOW64\config\systemprofile\桌面

Windows 2008 服务器 x86

C:\Windows\System32\config\systemprofile\桌面

我不确定为什么会这样,但它对我有用。我希望这对处于相同情况的人有所帮助,并感谢那些试图提供帮助的人。