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

mrm*_*oey 5 python excel xlrd

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

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

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

干杯

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

小智 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]
Run Code Online (Sandbox Code Playgroud)


Joh*_*hin 5

网上(或在您的计算机上打开文档并在浏览器中打开文档Ctrl-F #N/A)xlrd docs为您提供从Excel内部代码到文本转换表.

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


Cor*_*vax 5

如Andrew列出的那样,如果您在单元格中有错误,则xlrd会写出该错误的代码,您可以在此处看到:

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
Run Code Online (Sandbox Code Playgroud)

将代码0x2A从十六进制转换为dec可以得到该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)])
Run Code Online (Sandbox Code Playgroud)