在python3中处理xlswriter的Exception PermissionError

时间:2014-02-05 07:26:33

标签: python python-3.x xlsxwriter

我在我的Python3.3应用程序中使用XlsxWriter并且当打开excel文件并运行py脚本时发生此错误,除了except PermissionError之外我无法处理,

错误:

  

Exception PermissionError: PermissionError(13, 'Permission denied') in <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook object at 0x00000000032C3400>> ignored

我如何使用try来处理此错误?

2 个答案:

答案 0 :(得分:1)

您只需要在close()周围添加try / except来处理文件已被Excel打开并锁定的情况。

try:
    workbook.close()
except:
    # Handle your exception here.
    print("Couldn't create xlsx file")

如果需要,您可以为特定条件添加特定的异常处理程序。

答案 1 :(得分:0)

import xlsxwriter

try:
    # Create a workbook and add a worksheet.
    workbook = xlsxwriter.Workbook('Expenses01.xlsx')
    worksheet = workbook.add_worksheet()

    # Some data we want to write to the worksheet.
    expenses = (
        ['Rent', 1000],
        ['Gas',   100],
        ['Food',  300],
        ['Gym',    50],
    )

    # Start from the first cell. Rows and columns are zero indexed.
    row = 0
    col = 0

    # Iterate over the data and write it out row by row.
    for item, cost in (expenses):
        worksheet.write(row, col,     item)
        worksheet.write(row, col + 1, cost)
        row += 1

    # Write a total using a formula.
    worksheet.write(row, 0, 'Total')
    worksheet.write(row, 1, '=SUM(B1:B4)')

    workbook.close()
except:
    #
    #DO WHAT YOU WANT TO DO

试试这个。