编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

极客时间

尝试使用Python将Excel表格转换为PDF,但抛出此错误:Trying to convert excel sheets to PDF using Python but throwing up this error

alekzg Python 2022-5-11 10:48 5人围观

腾讯云服务器
尝试使用Python将Excel表格转换为PDF,但抛出此错误的处理方法

我正在尝试使用python将excel表格转换为pdf,转换了一个脚本,以对Word文档进行同样的处理,效果很好,但在举报下面有此错误

Hi I am trying to convert excel sheet to pdf using python, converted a script wrote to do same with word documents, which works fine but having this error below flagging up

Traceback (most recent call last): File "C:/Users/alank/Python training/Exceltopdf2.py", line 13, in <module> xlxs.SaveAs(out_file, FileFormat=xlxsFormatPDF) OSError: exception: access violation reading 0xFFFFFFFFFFFFFFFF 

任何帮助表示赞赏,脚本在下面

any help appreciated and script is below

import sys import os import comtypes.client xlxsFormatPDF = 17 in_file = (r'C:\Users\alank\Python training\Helloworld.xlsx') out_file = (r'C:\Users\alank\Python training\Helloworld.pdf') excel = comtypes.client.CreateObject('Excel.Application') xlxs = excel.workbooks.Open(in_file) xlxs.SaveAs(out_file, FileFormat=xlxsFormatPDF) xlxs.Close() excel.Quit() 

问题解答

您可以尝试使用 win32com.client 像这样:

You can try with win32com.client like this:

import win32com.client from pywintypes import com_error WB_PATH = r'C:\Users\alank\Python training\Helloworld.xlsx' PATH_TO_PDF = r'C:\Users\alank\Python training\Helloworld.pdf' excel.Visible = False try: # Open wb = excel.Workbooks.Open(WB_PATH) # Specify the sheet you want to save by index. #if you want all the sheets in excel try with: #wb.WorkSheets(wb.Sheets.Count) or wb.WorkSheets([i=1 for i in range(wb.Sheets.Count)]).Select() ws_index_list = [1,2,3,4,5,6,7,8,9,10,11,12] wb.WorkSheets(ws_index_list).Select() # Save wb.ActiveSheet.ExportAsFixedFormat(0, PATH_TO_PDF) except com_error as e: print('The convertion failed.') else: print('Succeessful convertion') finally: wb.Close() excel.Quit() 

或者您也可以像在此(Andreas解决方案):

import os import comtypes.client SOURCE_DIR = r'C:\Users\alank\Python training' TARGET_DIR = r'C:\Users\alank\Python training' app = comtypes.client.CreateObject('Excel.Application') app.Visible = False infile = os.path.join(os.path.abspath(SOURCE_DIR), 'Helloworld.xlsx') outfile = os.path.join(os.path.abspath(TARGET_DIR), 'Helloworld.pdf') doc = app.Workbooks.Open(infile) doc.ExportAsFixedFormat(0, outfile, 1, 0) doc.Close() app.Quit() 

这篇关于尝试使用Python将Excel表格转换为PDF,但抛出此错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^