我正在尝试从 Excel 文件自动创建 pdf 并每天通过电子邮件发送。它应该很简单,但事实并非如此。如果我在命令行中运行这些文件,它们将运行、创建 pdf,并正确关闭 excel。
但是如果我在任务计划程序中运行它,它不仅拒绝创建 pdf,而且 Excel 挂起并且无法正确退出。
我已经在 python 和 powershell 中尝试过了
Python wincom32
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
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
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($_)
}
}
}
powershell
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"
我用复杂的 Excel 文件和简单的 Excel 文件对其进行了测试。我的简单文件只是一个 book1.xlsx,单元格 A1 中带有 blah 一词。
我的任务管理器 我尝试过以下方法
[
[
还有这些设置
我尝试调查事件查看器,通过研究,我找到了这篇文章并按照步骤操作,但没有成功。 Excel 仍然挂在任务计划程序中,并且我的 pdf 未创建。 https://shauncasells.wordpress.com/2015/09/28/windows-10-event-10016-fix-the-application-specific-permission-settings-do-n ot-grant-local-activation-permission-for-the-com-server-application-with-clsid-d63b10c5-bb46-4990-a94f-e40b9d520160-and-a/
我也尝试过使用Python Schedule,但这仍然会导致excel挂在任务管理器中,并且也不会创建pdf。我不确定发生了什么事。
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)
我的目标是
我之前在某个地方见过类似的问题,并且有一些我通常使用的有效修复程序,以防万一。
time.sleep(value)
或 Close()
命令后,使 Python 与 Quit()
一起休眠一段时间(Excel 端的进程可能很长,并且在退出时会停止)。excelapp = w32cl.DispatchEx('Excel.Application')
wb = excelapp.Workbooks.Open(path)
...
wb.Close(True)
wb = None
excelapp.Quit()
excelapp = None
os
、psutil
或其他模块):excelapp = w32cl.DispatchEx('Excel.Application')
tid, pid = win32process.GetWindowThreadProcessId(excelapp.Hwnd)
...
os.kill(pid, signal.SIGTERM)