You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows任务计划程序运行Excel转PDF脚本时Excel挂起问题求助

Excel转PDF自动任务在Windows计划程序中失败的问题

直接在命令行运行相关脚本时,可正常生成PDF并关闭Excel;但通过Windows任务计划程序运行时,不仅无法生成PDF,Excel还会挂起无法正常退出。我需要实现每日自动将Excel文件转换为PDF并发送邮件的自动化流程,但目前遇到了上述问题。

已尝试的实现方式

1. Python win32com脚本

from os import getenv
from os.path import basename
from pathlib import Path
from datetime import datetime, timedelta, time
import pythoncom
import os
import shutil
import time
from win32com import client
import win32com.client as w3c


today = datetime.now().date()
path = "C:\\scripts\\"

excel_path = os.path.join(path , 'Book1.xlsx')
pdf_path = os.path.join(path ,'book1.pdf')

#convert to PDF
pythoncom.CoInitialize()
excel =  w3c.Dispatch("Excel.Application")
sheets =  excel.Workbooks.Open(excel_path)
work_sheets = sheets.Worksheets[1]
work_sheets.ExportAsFixedFormat(0, pdf_path)

sheets.Close(False)
excel.Workbooks.Close()
excel = None
pythoncom.CoUninitialize()

运行命令:

python c:\scripts\pycom.py

2. Python xlwings脚本

import os
import xlwings as xw

book = xw.Book(r'C:\\scripts\\Book1.xlsx')
sheet = book.sheets("Sheet1")

current_work_dir = os.getcwd()
pdf_path = os.path.join(current_work_dir, "Book1.pdf")

sheet.api.ExportAsFixedFormat(0, pdf_path)

app = xw.apps.active 
app.quit()

运行命令:

python c:\scripts\xlwings.py

3. PowerShell脚本

param (
    [parameter(Mandatory=$true)]
    [string]$ExcelFilePath,  # Path to the Excel file
    [parameter(Mandatory=$true)]
    [string]$WorksheetName,  # Name of the specific worksheet
    [parameter(Mandatory=$true)]
    [string]$OutputFolderPath  # Path where PDF files will be saved
)

try {
    $excel = New-Object -ComObject Excel.Application
    $excel.Visible = $false
    $excel.DisplayAlerts = $false

    $workbook = $excel.Workbooks.Open($ExcelFilePath)
    $worksheet = $workbook.Worksheets.Item($WorksheetName)

    # Generate the PDF file path (customize as needed)
    $pdfPath = Join-Path -Path $OutputFolderPath -ChildPath ($workbook.Name -replace '\.xlsx?', '.pdf')

    # Export as PDF
    $xlFixedFormat = "Microsoft.Office.Interop.Excel.XlFixedFormatType" -as [type]
    $worksheet.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $pdfPath)

    $workbook.Close()
    $excel.Quit()
}
finally {
    # Release COM objects
    $worksheet, $workbook, $excel | ForEach-Object {
        if ($_ -ne $null) {
            [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($_)
        }
    }
}

运行命令:

cd c:\scripts\
.\ConvertToPDF.ps1 -ExcelFilePath "c:\scripts\Book1.xlsx" -WorksheetName "Sheet1" -OutputFolderPath "c:\scripts\"

其他尝试

  • 通过bat文件运行Python脚本:
start "C:\Python3_10\python.exe" "C:\scripts\pycom.py"
  • 使用Python Schedule库调度脚本:
import schedule
import time
import subprocess

def xlwings_daily():
    subprocess.run(['python', 'xlwings.py'])
def pycom_daily():
    subprocess.run(['python', 'pycom.py'])

schedule.every().day.at('08:49').do(xlwings_daily)
schedule.every().day.at('08:55').do(pycom_daily)

while True:
    schedule.run_pending()
    time.sleep(1)

我测试过复杂Excel文件和仅含单元格A1内容为blah的简单文件Book1.xlsx,结果一致。在任务计划程序中,已尝试不同启动配置,勾选“使用最高权限运行”,调整COM权限,但问题依旧。

目标

  • 脚本每日自动运行;
  • 成功生成PDF文件;
  • Excel进程正常退出,不会挂起。

内容的提问来源于stack exchange,提问作者arsarc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:05:16