【问题标题】:Python - openpyxl wb.save() throwing a TypeErrorPython - openpyxl wb.save() 抛出 TypeError
【发布时间】:2021-05-04 13:14:58
【问题描述】:

我有一个 .xlsx,我正在尝试对其进行编辑,然后另存为不同的文件名。我打电话给wb.save("TestReport.xlsx"),但是我得到了一个TypeError。有趣的是,Python 确实使用我指定的文件名保存了一个 .xlsx 文档,但是 Excel 无法打开它。

File in Downloads Folder

Excel error

这是我的代码:

def formatReport():

    os.chdir("C:\\Users\\awentz\\Downloads")

    files = sorted(os.listdir(os.getcwd()), key=os.path.getmtime)
    report = files[-1]
    logging.debug(str(report))

    wb = openpyxl.load_workbook(report)
    ws = wb.active


    ws.delete_cols(1, 1)

    for row in ws.iter_rows(min_row=2, max_row=len(ws["A"]), min_col=4, max_col=4):
        for cell in row:
            if cell.value != "":
                cell.value = float(cell.value) / 1440
                cell.number_format = 20


    wb.save("TestReport.xlsx")
    wb.close()

这是错误:

Exception has occurred: TypeError
expected <class 'str'>
  File "C:\Users\awentz\Desktop\Python Workspace\PullDailyUsageReport.py", line 90, in formatReport
    wb.save("TestReport.xlsx")
  File "C:\Users\awentz\Desktop\Python Workspace\PullDailyUsageReport.py", line 102, in <module>
    formatReport()

【问题讨论】:

  • 您应该包含错误的完整回溯。
  • 我认为这是完整的追溯。这就是错误消息中的全部内容。除非你指的是我调用函数的第 102 行,但这实际上只是 formatReport()
  • 异常一定是在别处发生,我猜是在读取文件时,因为它看起来像描述符异常,代码中没有其他可能引发它。
  • 异常发生在我调用wb.save("TestReport.xlsx")的地方。如果这是一个描述符错误,我将如何解决这个问题?抱歉,我是新手,不能 100% 确定该错误的含义。
  • 尝试注释掉数字格式。这些肯定是某种字符串,20肯定是没有意义的。

标签: python excel openpyxl


【解决方案1】:

@Charlie Clark 是正确的。这是导致错误的 number_format 行。我把它注释掉了,错误就消失了。

【讨论】:

    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 2011-10-03
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 2021-10-07
    相关资源
    最近更新 更多