我一直在我的开发服务器中使用win32com
模块轻松地从xlsx
转换为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应用程序,它引发了以下错误:
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
?
我已经使用PDFWriter测试了xtopdf,但是使用此解决方案,您需要读取并迭代范围并逐行写入行。我想知道是否有类似于win32com.client的更直接的解决方案。
谢谢!
编辑:感谢您的投票,但这是一个比尝试加载难以找到的冗余脚本更有效的方法,并且在Python 2.7中是wrttien。
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文件在运行中转换并在我的应用程序上显示为图像缩略图。
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()
我一直在使用它,它工作正常