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

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

我看了一下string格式化方法,但是看不出这是怎么回事。

除了有一个脚本发现了生命的意义(42),谁能提出这个问题可能是什么?

干杯

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

xlrd文档(或在您的计算机上;在浏览器中打开文档并执行Ctrl-F #N/A )将Excel内部代码转换为文本 。

查看sheet.row_types()方法和Cell类文档可能是有用的,它们给出了sheet.row_types()和其他types返回的types数字之间的交叉引用。 请注意,对这些types数字进行testing通常比对这些值使用isinstance()更有效,并且使用types数字没有歧义。

我发现这很有用。 感谢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] 

如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 

将代码0x2A从hex转换为十二进制,你可以得到这个值。 为了避免这种情况,你可以在你的代码中使用这样的东西:

 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)])