```python import win32com.client import os def excel_to_pdf(input_file, output_file): # 确保输入文件存在 if not os.path.exists(input_file): raise FileNotFoundError(f"文件 {input_file} 不存在") # 创建 Excel 应用程序实例 excel = win32com.client.Dispatch("Excel.Application") excel.Visible = False # 不显示 Excel 窗口 try: # 打开 Excel 文件 wb = excel.Workbooks.Open(input_file) # 设置页面布局为 A4 横向,并将第一列单独放一页 for ws in wb.Worksheets: ws.PageSetup.Orientation = 2 # 2 表示横向 ws.PageSetup.PaperSize = 9 # 9 表示 A4 纸张 ws.PageSetup.FitToPagesWide = 1 # 将所有列调整到一页宽度 # ws.PageSetup.FitToPagesTall = 1 # 将所有行调整到一页高度 ws.PageSetup.PrintArea = ws.Columns(1).Address # 设置打印区域为第一列 # 保存为 PDF 文件 wb.ExportAsFixedFormat(0, output_file) # 0 表示 PDF 格式 except Exception as e: print(f"转换失败: {e}") finally: # 关闭工作簿和 Excel 应用程序 wb.Close(SaveChanges=False) excel.Quit() if __name__ == "__main__": base_dir = os.path.dirname(os.path.abspath(__file__)) input_file = os.path.join(base_dir, r"output_with_qrcode_images.xlsx") output_file = os.path.join(base_dir, r"output_with_qrcode_images.pdf") excel_to_pdf(input_file, output_file) print(f"文件已成功转换为 PDF: {output_file}") # 额外注意: # 1. 确保 Excel 版本与使用的 win32com 库兼容。 # 2. 处理可能出现的异常时,尽量详细地记录错误信息以便排查问题。 # 3. 对于打印区域的设置,根据实际需求可能需要进一步调整。 ``` [2025-03-10 15:48:12 | AI写代码神器 | 507点数解答]