Python - 将 XLSX 转换为 PDF [英] Python - Converting XLSX to PDF
问题描述
我一直在我的开发服务器中使用 win32com
模块来轻松地从 xlsx
转换为 pdf
:
I have always used win32com
module in my development server to easily convert from xlsx
to pdf
:
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()
但是,我已经在没有安装 Excel 应用程序的生产服务器中部署了我的 Django
应用程序,它引发了以下错误:
However, I have deployed my Django
app in production server where I don't have Excel application installed and it raises the following error:
File "C:virtualenvsstructuraldblibsite-packageswin32comclient\__init__.p
y", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,c
lsctx)
File "C:virtualenvsstructuraldblibsite-packageswin32comclientdynamic.py
", line 114, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "C:virtualenvsstructuraldblibsite-packageswin32comclientdynamic.py
", line 91, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.II
D_IDispatch)
com_error: (-2147221005, 'Invalid class string', None, None)
有什么好的替代方法可以在 Python 中将 xlsx
转换为 PDF
?
Is there any good alternative to convert from xlsx
to PDF
in Python?
我已经使用 PDFWriter 测试了 xtopdf,但是使用此解决方案,您需要逐行读取和迭代范围并写入行.不知道有没有类似win32com.client的更直接的解决方法.
I have tested xtopdf with PDFWriter, but with this solution you need to read and iterate the range and write lines one by one. I wonder if there is a more direct solution similar to win32com.client.
谢谢!
推荐答案
As my original answer 被删除了,最终有点用,我在这里重新发布.
As my original answer was deleted and is eventually a bit useful, I repost it here.
您可以分 3 个步骤完成:
- 擅长熊猫:pandas.read_excel
- pandas 到 HTML:pandas.DataFrame.to_html
- 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")
安装:
sudo pip3.6 install pandas xlrd pdfkit
sudo apt-get install wkhtmltopdf
这篇关于Python - 将 XLSX 转换为 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!