MacOS环境下使用Python将Excel转为PDF并保留原格式的方法咨询
解决方案
你现有代码丢失格式的核心原因是仅提取了Excel单元格的数值,没有读取配色、字体加粗等样式属性,以下是两种可落地的实现方案:
方案1:优化现有HTML中转流程,手动注入样式
你可以用openpyxl读取单元格的样式属性,转换为CSS内联样式写入生成的HTML文件,再转PDF即可保留格式,参考实现代码:
from openpyxl import load_workbook import pdfkit as pdf import pandas as pd # 读取Excel wb = load_workbook(filename = '4-Grain Advertising Report.xlsx', data_only=True) ws = wb['Advertising 4 Grain P&L'] cell_range = ws['K9':'S31'] # 生成带样式的HTML内容 html_content = '<table border="1" cellpadding="5" cellspacing="0">' for row in cell_range: html_content += '<tr>' for cell in row: # 提取样式 style = [] # 加粗样式 if cell.font.bold: style.append('font-weight: bold;') # 单元格背景色 if cell.fill.start_color.rgb is not None and cell.fill.start_color.rgb != '00000000': # 取RGB后6位 color = cell.fill.start_color.rgb[2:] style.append(f'background-color: #{color};') # 字体颜色 if cell.font.color and cell.font.color.rgb: font_color = cell.font.color.rgb[2:] style.append(f'color: #{font_color};') # 拼接样式 style_str = ' '.join(style) cell_val = str(cell.value) if cell.value is not None else '' html_content += f'<td style="{style_str}">{cell_val}</td>' html_content += '</tr>' html_content += '</table>' # 写入HTML文件 with open('test.html', 'w', encoding='utf-8') as f: f.write(html_content) # 转PDF,添加参数避免权限问题 options = { 'enable-local-file-access': None, 'encoding': "UTF-8" } pdf.from_file('test.html', 'test_output.pdf', options=options)
如果需要保留对齐、边框等其他样式,可继续扩展读取openpyxl的cell.alignment、cell.border等属性补充CSS规则即可。
方案2:调用本地Office程序直接转换(更推荐)
Mac环境下直接调用原生Microsoft Excel或自带的Numbers程序导出PDF,可100%保留原Excel所有格式,不需要手动处理任何样式规则,参考实现(需要先安装Microsoft Excel):
import subprocess # 配置参数 excel_path = "/Users/xxx/4-Grain Advertising Report.xlsx" sheet_name = "Advertising 4 Grain P&L" output_pdf = "/Users/xxx/test_output.pdf" select_range = "K9:S31" # AppleScript脚本调用Excel导出 script = f''' tell application "Microsoft Excel" open POSIX file "{excel_path}" tell worksheet "{sheet_name}" of active workbook set exportRange to range "{select_range}" export as fixed format exportRange type PDF file name POSIX file "{output_pdf}" end tell close active workbook saving no end tell ''' # 执行脚本 subprocess.run(['osascript', '-e', script], capture_output=True, text=True)
该方案导出的PDF格式和你手动在Excel里选中范围导出的效果完全一致,适配所有复杂格式场景。
内容的提问来源于stack exchange,提问作者Kaushik Rajan
相关产品推荐
相关产品推荐

