Python xlsx转pdf问题

我正在尝试将xlsx文件转换为pdf格式。我以前有过它的工作,但现在我在代码底部收到了错误消息。它会将选定的xlsx转换为损坏的pdf(0个bty)。如果有人可以帮助我解决此问题,非常感谢( 如果您有任何疑问,请告诉我,不要解雇我,我是新来的。

编码:

print('\nStarting XLSX to PDF...\n\nLoading required libaries...', end='', flush=True)
import os               # Windows/Linux OS import
import sys, getopt      # System import for command line arguments
import openpyxl         # excel library
import win32com.client  # pdf library

o = win32com.client.Dispatch("Excel.Application")
o.Visible = False

print('done.\n')

def exit_main(emess,stat,se_flag):
    if emess:
        print(emess)
    print('STAT CODE:' + str(stat) + '\n')
    sys.exit(se_flag)

def main(argv):    
    stat = 0    
    ifile = ''      #input file
    ofile = ''      #output file
    sname = ''      #worksheet name
    eflag = False
    se_flag = ''
    pname = 'xlsx.to.pdf.py'
    emess = '\n\nUSAGE\n=====\n\npython ' + pname + ' -e <excelfiletoconvert> '
    emess = emess + '-s <worksheetname>(OPTIONAL) -p <pdfoutputfile>\n'

    try:
        opts, args = getopt.getopt(argv,'he:p:s:',['efile=','pfile=','sname='])
    except getopt.GetoptError:
        eflag = True
        se_flag = 2
        opts = ''
    for opt, arg in opts:
        if opt == '-h':
            emess = '\nHelp\n===='
            eflag = True

        elif opt in ('-e', '--efile'):
            ifile = arg
        elif opt in ('-p', '--pfile'):
            ofile = arg
        elif opt in ('-s', '--sname'):
            sname = arg
    if not ifile:
        eflag = True
        emess += '\nExcel file and location not specified -e'

    if not ofile:
        eflag = True
        emess += '\nPDF file and location not specified -p'

    if eflag is True:
        emess += '\nIf a worksheet (-s) is not specified then the first worksheet will be '
        emess += 'picked for conversion\n'
        exit_main(emess,stat,se_flag)

    else:    
        ##Open the xlsx file
        print('\nLoading Workbook <' + ifile + '>...', end='', flush=True)
        try:
            wb = openpyxl.load_workbook(ifile)
        except:
            emess = '\n\nCould not open Excel file <' + ifile + '>\n'
            emess += 'Please check filename and path.\n'
            exit_main(emess,stat,se_flag)
        else:
            print("done.\n")
            if not sname:
                sname = wb.sheetnames[0]
            try:
                sheet = wb[sname]
            except:
                emess = '\nWorksheet <' + sname + '> does not exist in Excel Workbook <' + ifile + '>\n'
                emess += 'Please check and try again.\n'
                exit_main(emess,stat,se_flag)
            else:
                #convert to PDF
                print('\nConverting Worksheet <' + sname + '> from Workbook <' + ifile + '> to PDF...', end='', flush=True)
                with open(ofile,'w',newline='') as f:  
                    wb_path = ifile
                    path_to_pdf = ofile
                    wb = o.Workbooks.Open(wb_path)
                    wb.ActiveSheet.ExportAsFixedFormat(0, path_to_pdf) 
                    o.Quit()
                    print('done.\n')
                    print('PDF location <' + ofile + '>')
                    stat = 1
                    emess = ''
                exit_main(emess,stat,se_flag)
if __name__ == '__main__':
   main(sys.argv[1:])

输出:

USAGE
=====
python xlsx.to.pdf.py -e <excelfiletoconvert> -s <worksheetname>(OPTIONAL) -p <pdfoutputfile>

Excel file and location not specified -e
PDF file and location not specified -p
If a worksheet (-s) is not specified then the first worksheet will be picked for conversion

STAT CODE:0


PS C:\Users\jordan\desktop\visualstudio> python xlsx.to.pdf.py -e C:\users\jordan\desktop\excel100.xlsx -p C:\users\jordan\desktop\testfile.pdf

Loading Workbook <C:\users\jordan\desktop\excel100.xlsx>...done.


Converting Worksheet <Sheet1> from Workbook <C:\users\jordan\desktop\excel100.xlsx> to PDF...Traceback (most recent call last):
  File "xlsx.to.pdf.py", line 113, in <module>
    main(sys.argv[1:])
  File "xlsx.to.pdf.py", line 105, in main
    wb.ActiveSheet.ExportAsFixedFormat(0, path_to_pdf)
  File "<COMObject <unknown>>", line 4, in ExportAsFixedFormat
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Document not saved.', 'xlmain11.chm', 0, -2147018887), None)
PS C:\Users\jordan\desktop\visualstudio>
评论