import os import win32com.client path = r'C:\Users\Administrator\Desktop\pr\2\5E2206172401600B' if not os.path.exists(path): print('路径不存在!') else: for root, dirs, files in os.walk(path): for file in files: if file.endswith('.xlsx') or file.endswith('.xls'): try: excel = win32com.client.Dispatch('Excel.Application') workbook = excel.Workbooks.Open(os.path.join(root, file)) workbook.ExportAsFixedFormat(0, os.path.join(root, os.path.splitext(file)[0] + '.pdf')) workbook.Close() excel.Quit() del excel # 删除该对象,释放内存 except Exception as e: print('转换文件 %s 出错:%s' % (file, e)) print('执行结束!')
时间: 2024-02-14 17:15:15 浏览: 111
以下是类似功能的VBA代码,可以将一个文件夹下的Excel文件转换为PDF格式:
```
Sub ConvertExcelToPDF()
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Dim folder_path As String
folder_path = "C:\Users\Administrator\Desktop\pr\2\5E2206172401600B"
If Not fs.FolderExists(folder_path) Then
MsgBox "路径不存在!"
Exit Sub
End If
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim excel_app As Object
Dim workbook As Object
Dim file As Object
For Each file In fso.GetFolder(folder_path).Files
If LCase(Right(file.Name, 4)) = "xlsx" Or LCase(Right(file.Name, 3)) = "xls" Then
On Error Resume Next
Set excel_app = CreateObject("Excel.Application")
Set workbook = excel_app.Workbooks.Open(file.Path)
workbook.ExportAsFixedFormat 0, Replace(file.Path, ".xlsx", ".pdf")
workbook.Close False
excel_app.Quit
Set excel_app = Nothing
Set workbook = Nothing
On Error GoTo 0
End If
Next file
MsgBox "执行结束!"
End Sub
```
请注意,VBA代码中使用的对象与方法与Python代码中略有不同。如果您需要更多帮助,请告诉我。
阅读全文