python读取excel文档报raise CompDocError错误

错误提示

  File "/home/xxxx/anaconda3/lib/python3.7/site-packages/xlrd/compdoc.py", line 426, in _locate_stream
    raise CompDocError("%s corruption: seen[%d] == %d" % (qname, s, self.seen[s]))
xlrd.compdoc.CompDocError: Workbook corruption: seen[2] == 4

使用xlrd读取excel文档时,报如上错误;经过测试,pandas也是使用的xlrd进行excel文档读写,所以问题也是一样。

问题原因

对于我来说,这个错误的原因应该是excel文档包含的列太多了,xlrd做了保护,删除部分列后读写就正常了。

解决办法

如果要解决这个问题,可以试试没有使用xlrd的库,或者直接修改源代码,把抛异常的地方注释掉。
例如:
方法一:使用win32com库,已有网友验证是没有问题的,可以参考:https://www.cnblogs.com/hankleo/p/11684531.html
方法二:直接修改源码也是可以解决的,可以参考:http://www.python66.com/bbs/132.html

补充说明

上面的方法一应该只能在window系统有效,我的是linux系统,用的是linux版的wps,没有装wine和excel,估计无法使用,这个是估计,没有实测。主要是我实测了xlwings,这个在linux系统也无法正常运行,初始化app就出错,它的操作excel的原理应该跟win32com类似。
在linux系统可以使用openpyxl来解决,不过,openpyxl只能处理xlsx格式,无法处理xls格式,代码如下(合并多个excel文件):

def merge_xlsx(file_list, target_file):
    print(file_list)
    line_count = 0
    new_wb = openpyxl.Workbook()
    new_ws = new_wb.active
    for file_name in file_list:
        print("line begin : %d, merging %s..." % (line_count, file_name))
        wb = openpyxl.load_workbook(file_name)
        ws = wb.active
        title_line = line_count+1
        for row in ws.rows:
            rv = [cell.value for cell in row]
            new_ws.append(rv)
            line_count += 1
        # 删除重复的title
        if title_line != 1:
            new_ws.delete_rows(title_line)
            line_count -= 1
    print("total line %d, saved to %s" % (line_count, target_file))
    new_wb.save(target_file)

你可能感兴趣的:(python,python,xlrd,excel,openpyxl)