xlrd Excel脚本将“#N / A”转换为42

问题描述 投票:5回答:3

我有一个脚本使用xlrd模块从excel电子表格中提取数据,特别是row_values()方法。它似乎做得很好,除了之前的VLookups已经自动生成“#N / A”,在这种情况下,xlrd将“#N / A”作为整数42。

我看了一下字符串格式化方法,但看不出那是怎么回事。

除了有一个发现了生命意义的脚本(42)之外,有谁可以建议问题是什么?

干杯

注意:工作表中不再包含Vlookups,所有值都已从其他工作表复制,一切都是普通值,没有公式。

python excel xlrd
3个回答
5
投票

在网络上(或在您的计算机上打开文档;在浏览器中打开文档并执行Ctrl-F #N/A)为您提供conversion table from Excel internal codes to text

查看sheet.row_types() methodCell class docs可能会有用,它会为您提供由sheet.row_types()和其他人返回的类型编号之间的交叉引用。请注意,测试这些类型数字通常比在值上使用isinstance()更有效,并且使用类型编号没有歧义。


10
投票

我发现这很有用。感谢John的初步帮助。

def xls_proc_text(cell, value_proc=None, text_proc=None):
    """Converts the given cell to appropriate text."""
    """The proc will come in only when the given is value or text."""
    ttype = cell.ctype
    if ttype == xlrd.XL_CELL_EMPTY or ttype == xlrd.XL_CELL_TEXT or ttype == xlrd.XL_CELL_BLANK:
        if text_proc is None:
            return cell.value
        else:
            return text_proc(cell.value)
    if ttype == xlrd.XL_CELL_NUMBER or ttype == xlrd.XL_CELL_DATE or ttype == xlrd.XL_CELL_BOOLEAN:
        if value_proc is None:
            return str(cell.value)
        else:
            return str(value_proc(cell.value))
    if cell.ctype == xlrd.XL_CELL_ERROR:
        # Apply no proc on this.
        return xlrd.error_text_from_code[cell.value]

4
投票

正如安德鲁列出的那样,如果你在单元格中有错误,xlrd会写错误的代码,你可以看到here

0x00: '#NULL!',  # Intersection of two cell ranges is empty
0x07: '#DIV/0!', # Division by zero
0x0F: '#VALUE!', # Wrong type of operand
0x17: '#REF!',   # Illegal or deleted cell reference
0x1D: '#NAME?',  # Wrong function or range name
0x24: '#NUM!',   # Value range overflow
0x2A: '#N/A',    # Argument or function not available

将代码0x2A从十六进制转换为十进制,您可以获得该值42。为避免这种情况,您可以在代码中使用以下内容:

for rownum in xrange(sh.nrows):
    wr.writerow(['#N/A' if col.ctype == xlrd.XL_CELL_ERROR else col.value for col in sh.row(rownum)])
© www.soinside.com 2019 - 2024. All rights reserved.