簡體   English   中英

嘗試使用 Python 將 excel 表轉換為 PDF 但拋出此錯誤

[英]Trying to convert excel sheets to PDF using Python but throwing up this error

嗨,我正在嘗試使用 python 將 excel 工作表轉換為 pdf,轉換了一個編寫為對 word 文檔執行相同操作的腳本,它工作正常,但在標記下方有此錯誤

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

任何幫助表示贊賞,腳本如下

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

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM