You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将XLSXWriter生成的内存XLSX文件转为PDF

内存中XLSX转PDF字节流的Python实现方案

以下是几种可行的实现方案,覆盖不同平台和依赖场景:

方案1:pywin32(仅Windows平台,依赖微软Excel)

利用Windows的COM接口调用本地Excel程序完成转换,格式还原度最高,但仅支持Windows环境。

依赖安装

pip install pywin32

代码实现

import win32com.client
from io import BytesIO
import tempfile
import os

def xlsx_bytes_to_pdf_bytes(xlsx_bytes):
    # 将内存中的XLSX写入临时文件
    with tempfile.NamedTemporaryFile(suffix='.xlsx', delete=False) as tmp_xlsx:
        tmp_xlsx.write(xlsx_bytes)
        tmp_xlsx_path = tmp_xlsx.name

    # 初始化Excel COM对象
    excel = win32com.client.Dispatch("Excel.Application")
    excel.Visible = False
    excel.DisplayAlerts = False

    try:
        # 打开临时XLSX文件
        workbook = excel.Workbooks.Open(tmp_xlsx_path)
        # 生成临时PDF路径
        tmp_pdf_path = tmp_xlsx_path.replace('.xlsx', '.pdf')
        # 导出为PDF
        workbook.ExportAsFixedFormat(0, tmp_pdf_path)
        workbook.Close()

        # 读取PDF内容到字节流
        with open(tmp_pdf_path, 'rb') as f:
            pdf_bytes = f.read()
    finally:
        # 确保Excel进程退出
        excel.Quit()
        # 清理临时文件
        os.unlink(tmp_xlsx_path)
        if os.path.exists(tmp_pdf_path):
            os.unlink(tmp_pdf_path)
    
    return pdf_bytes

# 示例调用(假设你已经有了xlsx_bytes)
# xlsx_bytes = ... # 你的XLSXWriter生成的BytesIO.getvalue()
# pdf_bytes = xlsx_bytes_to_pdf_bytes(xlsx_bytes)

方案2:LibreOffice/OpenOffice命令行调用(跨平台)

借助LibreOffice的命令行工具完成转换,支持Windows、Linux、macOS,无需依赖微软Excel,但需要预先安装LibreOffice。

依赖准备

  1. 安装LibreOffice/OpenOffice
  2. 确保soffice(Linux/macOS)或soffice.exe(Windows)在系统PATH中

代码实现

from io import BytesIO
import tempfile
import os
import subprocess

def xlsx_bytes_to_pdf_bytes(xlsx_bytes):
    # 创建临时目录存放文件
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_xlsx_path = os.path.join(tmp_dir, 'input.xlsx')
        tmp_pdf_path = os.path.join(tmp_dir, 'output.pdf')

        # 写入内存XLSX到临时文件
        with open(tmp_xlsx_path, 'wb') as f:
            f.write(xlsx_bytes)

        # 调用LibreOffice命令转换
        cmd = [
            'soffice',
            '--headless',
            '--convert-to', 'pdf',
            '--outdir', tmp_dir,
            tmp_xlsx_path
        ]
        subprocess.run(cmd, check=True, capture_output=True)

        # 读取PDF字节流
        with open(tmp_pdf_path, 'rb') as f:
            pdf_bytes = f.read()
    
    return pdf_bytes

# 示例调用
# xlsx_bytes = ...
# pdf_bytes = xlsx_bytes_to_pdf_bytes(xlsx_bytes)

方案3:openpyxl + pdfkit(跨平台,样式还原度一般)

先通过openpyxl读取内存中的XLSX,将工作表内容转为HTML,再用pdfkit将HTML转为PDF。这种方案无需依赖办公软件,但表格样式、格式还原度可能不如前两种方案。

依赖安装

pip install openpyxl pdfkit

同时需要安装wkhtmltopdf,并确保其在系统PATH中。

代码实现

from io import BytesIO
import openpyxl
import pdfkit
from openpyxl.utils import get_column_letter

def xlsx_bytes_to_pdf_bytes(xlsx_bytes):
    # 读取内存中的XLSX
    wb = openpyxl.load_workbook(BytesIO(xlsx_bytes))
    ws = wb.active

    # 生成HTML表格
    html = '<html><body><table border="1">'
    # 写入表头
    html += '<tr>'
    for cell in ws[1]:
        html += f'<th>{cell.value}</th>'
    html += '</tr>'
    # 写入数据行
    for row in ws.iter_rows(min_row=2):
        html += '<tr>'
        for cell in row:
            html += f'<td>{cell.value}</td>'
        html += '</tr>'
    html += '</table></body></html>'

    # 将HTML转为PDF字节流
    pdf_bytes = pdfkit.from_string(html, False)
    return pdf_bytes

# 示例调用
# xlsx_bytes = ...
# pdf_bytes = xlsx_bytes_to_pdf_bytes(xlsx_bytes)

内容的提问来源于stack exchange,提问作者Vizionet333

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 14:45:37