大家好我有一个程序,它创建并保存一个xlsx文件,然后打开它并转换为pdf ...但我希望它删除原始的xlsx文件。
wb.save(NEW_RECEIPT_PATH + new_file_name_xlsx)
#this should turn the xlsx into a pdf
xlApp = client.Dispatch("Excel.Application")
books = xlApp.Workbooks.Open(NEW_RECEIPT_PATH + new_file_name_xlsx)
ws2 = books.Worksheets[0]
ws2.Visible = 1
save_the_pdf = NEW_RECEIPT_PATH + new_file_name_pdf
ws2.ExportAsFixedFormat(0,save_the_pdf)
#this removes the xlsx file
os.remove(NEW_RECEIPT_PATH + new_file_name_xlsx)
我的预感是我没有在正确的位置使用.close(),而只是将excel文件保持打开状态。我试过了...
wb.save(NEW_RECEIPT_PATH + new_file_name_xlsx)
wb.close()
#this should turn the xlsx into a pdf
xlApp = client.Dispatch("Excel.Application")
books = xlApp.Workbooks.Open(NEW_RECEIPT_PATH + new_file_name_xlsx)
ws2 = books.Worksheets[0]
ws2.Visible = 1
save_the_pdf = NEW_RECEIPT_PATH + new_file_name_pdf
ws2.ExportAsFixedFormat(0,save_the_pdf)
#this removes the xlsx file
os.remove(NEW_RECEIPT_PATH + new_file_name_xlsx)
无济于事。任何线索将不胜感激。
-update-
我已经确定了这些问题......
#this should turn the xlsx into a pdf
xlApp = client.Dispatch("Excel.Application")
books = xlApp.Workbooks.Open(NEW_RECEIPT_PATH + new_file_name_xlsx)
ws2 = books.Worksheets[0]
ws2.Visible = 1
save_the_pdf = NEW_RECEIPT_PATH + new_file_name_pdf
ws2.ExportAsFixedFormat(0,save_the_pdf)
xlsx文件保持打开状态,不允许我通过代码删除它...与手动删除xlsx文件相同。我必须双击该文件才能将其打开,然后在我删除之前将其关闭。
如何在此代码的末尾关闭xlsx文件?
放心......我以为我没有正确关闭它。下面的代码非常出色。
该死,我讨厌被困几天。
#this should turn the xlsx into a pdf
xlApp = client.Dispatch("Excel.Application")
books = xlApp.Workbooks.Open(NEW_RECEIPT_PATH + new_file_name_xlsx)
ws2 = books.Worksheets[0]
ws2.Visible = 1
save_the_pdf = NEW_RECEIPT_PATH + new_file_name_pdf
ws2.ExportAsFixedFormat(0,save_the_pdf)
books.Close(True) # save the workbook
#this removes the xlsx file
os.remove(NEW_RECEIPT_PATH + new_file_name_xlsx)