大家好,我有一个程序可以创建并保存一个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)
无济于事。任何线索将不胜感激。
-更新-
我已经确定问题出在这些方面...
#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文件?
答案 0 :(得分:0)
放心,伙计们……我以为我没有正确关闭它。下面的代码非常出色。
该死,我讨厌被困几天。
#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)