import os
import sys
from openpyxl import load_workbook
from fpdf import FPDF
<details>
<summary>点击查看代码</summary>
</details>
def excel_to_pdfs(excel_file_path):
# 加载工作簿
try:
wb = load_workbook(excel_file_path)
except Exception as e:
print(f"无法加载Excel文件: {e}")
return
# 获取Excel文件的基本名称(不包含扩展名)
base_name = os.path.splitext(os.path.basename(excel_file_path))[0]
# 创建输出目录
output_dir = f"{base_name}_sheets_pdfs"
os.makedirs(output_dir, exist_ok=True)
# 遍历每个工作表
for sheet_name in wb.sheetnames:
sheet = wb[sheet_name]
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
# 获取工作表的最大行数和列数
max_row = sheet.max_row
max_col = sheet.max_column
# 设置单元格的宽度和高度
cell_width = 190 / max_col # A4宽度为210mm,减去左右边距各10mm
cell_height = 10
# 遍历工作表的每一行和每一列
for row_idx in range(1, max_row + 1):
for col_idx in range(1, max_col + 1):
cell = sheet.cell(row=row_idx, column=col_idx)
value = str(cell.value) if cell.value is not None else ""
# 写入单元格内容
pdf.cell(cell_width, cell_height, txt=value, border=1)
# 换行
pdf.ln(cell_height)
# 保存PDF文件
pdf_path = os.path.join(output_dir, f"{base_name}_{sheet_name}.pdf")
try:
pdf.output(pdf_path)
print(f"已生成PDF: {pdf_path}")
except Exception as e:
print(f"生成PDF失败 {sheet_name}: {e}")
print(f"所有工作表已转换为PDF并保存在目录: {output_dir}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("使用方法: python excel_sheet_to_pdf.py <excel文件路径>")
sys.exit(1)
excel_file = sys.argv[1]
# 检查文件是否存在
if not os.path.isfile(excel_file):
print(f"错误: 文件 '{excel_file}' 不存在")
sys.exit(1)
# 检查文件是否为Excel文件
if not excel_file.lower().endswith(('.xlsx', '.xls')):
print(f"错误: 文件 '{excel_file}' 不是Excel文件")
sys.exit(1)
excel_to_pdfs(excel_file)