Python-将XLSX转换为PDF

Dav*_*uez 5 python pdf django xlsx win32com

我一直win32com在开发服务器中使用模块来轻松地从转换xlsxpdf

o = win32com.client.Dispatch("Excel.Application")
o.Visible = False
o.DisplayAlerts = False
wb = o.Workbooks.Open("test.xlsx")))
wb.WorkSheets("sheet1").Select()
wb.ActiveSheet.ExportAsFixedFormat(0, "test.pdf")
o.Quit()
Run Code Online (Sandbox Code Playgroud)

但是,我已经Django在没有安装Excel应用程序的生产服务器中部署了我的应用程序,这会引发以下错误:

File "C:\virtualenvs\structuraldb\lib\site-packages\win32com\client\__init__.p
y", line 95, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,c
lsctx)
  File "C:\virtualenvs\structuraldb\lib\site-packages\win32com\client\dynamic.py
", line 114, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "C:\virtualenvs\structuraldb\lib\site-packages\win32com\client\dynamic.py
", line 91, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.II
D_IDispatch)
com_error: (-2147221005, 'Invalid class string', None, None)
Run Code Online (Sandbox Code Playgroud)

在Python中是否有很好的替代方法可以将转换xlsxPDF

我已经使用PDFWriter测试了xtopdf,但是使用此解决方案,您需要读取和迭代范围并逐行写入行。我想知道是否有类似于win32com.client的更直接的解决方案。

谢谢!

Tho*_*gdt 6

由于我的原始答案已被删除并且最终有点用处,因此我将其重新发布在这里。

您可以分 3 步完成:

  1. excel到熊猫:pandas.read_excel
  2. 熊猫到 HTML:pandas.DataFrame.to_html
  3. HTML 到 pdf: python-pdfkit (git) , python-pdfkit (pypi.org)
import pandas as pd
import pdfkit

df = pd.read_excel("file.xlsx")
df.to_html("file.html")
pdfkit.from_file("file.html", "file.pdf")
Run Code Online (Sandbox Code Playgroud)

安装:

sudo pip3.6 install pandas xlrd pdfkit
sudo apt-get install wkhtmltopdf 
Run Code Online (Sandbox Code Playgroud)

  • 这适用于包含图像、公式和格式的 Excel 文件吗? (2认同)

thi*_*054 2

from openpyxl import load_workbook
from PDFWriter import PDFWriter

workbook = load_workbook('fruits2.xlsx', guess_types=True, data_only=True)
worksheet = workbook.active

pw = PDFWriter('fruits2.pdf')
pw.setFont('Courier', 12)
pw.setHeader('XLSXtoPDF.py - convert XLSX data to PDF')
pw.setFooter('Generated using openpyxl and xtopdf')

ws_range = worksheet.iter_rows('A1:H13')
for row in ws_range:
    s = ''
    for cell in row:
        if cell.value is None:
            s += ' ' * 11
        else:
            s += str(cell.value).rjust(10) + ' '
    pw.writeLine(s)
pw.savePage()
pw.close()
Run Code Online (Sandbox Code Playgroud)

我一直在使用这个并且效果很好