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()
但是,我已经将我的Django
应用程序部署到了没有安装Excel应用程序的生产服务器中,这会引发以下错误:
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:\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)
在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.
谢谢!
推荐答案
感谢您的不赞成票,但这是一种比试图加载一个在Python 2.7中很难找到并且很烂的冗余脚本有效得多的方法.
Thanks for the down vote but this is a far more efficient method than trying to load a redundant script that is hard to find and was wrttien in Python 2.7.
- 将Excel电子表格加载到DataFrame中
- 将DataFrame写入HTML文件
- 将html文件转换为图像.
dirname, fname = os.path.split(source)
basename = os.path.basename(fname)
data = pd.read_excel(source).head(6)
css = """
"""
text_file = open(f"{basename}.html", "w")
# write the CSS
text_file.write(css)
# write the HTML-ized Pandas DataFrame
text_file.write(data.to_html())
text_file.close()
imgkitoptions = {"format": "jpg"}
imgkit.from_file(f"{basename}.html", f'{basename}.png', options=imgkitoptions)
try:
os.remove(f'{basename}.html')
except Exception as e:
print(e)
return send_from_directory('./', f'{basename}.png')
来自此处 https://medium.com/@andy.lane/convert-pandas-dataframes-to-images-using-imgkit-5da7e5108d55
效果很好,我可以即时转换XLSX文件并在应用程序中显示为图像缩略图.
Works really well, I have XLSX files converting on the fly and displaying as image thumbnails on my application.
这篇关于Python-将XLSX转换为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!