# 批量转换excel2pdf-python **Repository Path**: myhfw003/batch-conversion-excel2pdf-python ## Basic Information - **Project Name**: 批量转换excel2pdf-python - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-04-12 - **Last Updated**: 2025-04-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 批量转换excel2pdf-python,并且根据excel宽度自动调整页面设置为横向或者纵向,再批量转换为pdf,该脚本已经测试可用,可根据自己需要进行扩展 1. 安装依赖库 ```python pip install pywin32 openpyxl ``` 2. 创建一个名为:excel2pdf的python文件,输入如下代码 ```python import os import win32com.client as win32 def smart_export_pdf(input_folder, output_folder): excel = win32.gencache.EnsureDispatch("Excel.Application") excel.Visible = False # A4纸尺寸(单位:磅) A4_PORTRAIT_WIDTH = 595.44 # 21cm A4_LANDSCAPE_WIDTH = 841.68 # 29.7cm for file in os.listdir(input_folder): if not file.lower().endswith(('.xlsx', '.xls')): continue # 打开文件 file_path = os.path.join(input_folder, file) wb = excel.Workbooks.Open(file_path) ws = wb.Sheets(1) # 设置页边距 ws.PageSetup.LeftMargin = excel.InchesToPoints(0.5) ws.PageSetup.RightMargin = excel.InchesToPoints(0.5) # 计算内容宽度 used_range = ws.UsedRange content_width = used_range.Width # 获取内容总宽度(磅) # 判断是否超宽 margin_total = ws.PageSetup.LeftMargin + ws.PageSetup.RightMargin if content_width > (A4_PORTRAIT_WIDTH - margin_total): ws.PageSetup.Orientation = 2 # 横向 ws.PageSetup.PaperSize = 9 # A4 else: ws.PageSetup.Orientation = 1 # 纵向 # 强制宽度缩放 ws.PageSetup.Zoom = False ws.PageSetup.FitToPagesWide = 1 ws.PageSetup.FitToPagesTall = 1 # 高度自适应 # 保存PDF pdf_name = os.path.splitext(file)[0] + ".pdf" pdf_path = os.path.join(output_folder, pdf_name) wb.ExportAsFixedFormat(0, pdf_path) wb.Close(False) excel.Quit() filePath=r"E:\\myGitProject\bulkProcessExcel\\开发方向" # 使用示例 smart_export_pdf(filePath,filePath) print("转换完成!PDF已根据内容宽度自动调整方向。") ``` 3. 更换excel所在路径,就会输出pdf