zoukankan      html  css  js  c++  java
  • 【Python】xlrd,NotImplementedError-formatting_info=True not yet implemented

    前言

    Python需要读取Excel(.xls、.xlsx)时通常使用xlrd模块;如果要对其内容进行编辑的话稍稍有些麻烦,通常的做法是使用xlutils的copy模块对原文件进行复制,然后保存成新的文件。

    使用示例

    from xlutils import copy
    import xlrd
    import time
    import os
    
    def save_result(file_path,res_flags,request_urls,responses):
        book = xlrd.open_workbook(file_path)  # 读取Excel
        new_book = copy.copy(book)  # 复制读取的Excel
        sheet = new_book.get_sheet(0)
        i = 1
        for request_url, response, flag in zip(request_urls, responses, res_flags):
            sheet.write(i, 8, u'%s' % request_url)
            sheet.write(i, 9, u'%s' % response)
            sheet.write(i, 10, u'%s' % flag)
            i += 1
        report_path = os.path.abspath(os.path.join('report'))
        if not os.path.exists(report_path):
            os.makedirs(report_path)
        new_book.save(os.path.abspath(os.path.join(report_path, 'Report@%s.xlsx' % time.strftime('%Y.%m.%d@%H%M%S'))))  # 保存为新的Excel
    

    以上的示例适用于普通场景,假如xlsx较复杂,夹杂着各种格式、规则、宏,可能就会遇到问题---普通读取会丢掉所有这些附带的信息

    其实xlrd早就已经适配了这个功能,它提供的formatting_info参数取值为True时(为了节省内存,该参数默认为False),就会读取各种格式的信息。

    使用方法

    xlrd.open_workbook(file,formatting_info=True) # 读取Excel
    

    但是我们会发现在读取xlsx格式的Excel时,传入formatting_info会直接抛出异常,而读取xls类型的文件时不存在此问题。

    raise NotImplementedError("formatting_info=True not yet implemented")
    

    不难推断,抛异常的原因是formatting_info还没有对新版本的xlsx的格式完成兼容。

    那么如果我们要操作的文件刚好是xlsx格式,又想保存其原有的格式该怎么办呢?

    解决方法

    1、修改为xlsx为xls(推荐)

    将xlsx另存为xls,然后再进行后续操作,亲测有效,能正常保存Excel原有格式, 不用修改代码。

    2、改用 openpyxl

    coding尝试读取文件,处理速度真的很慢...而且规则和宏全部丢失。

    3、使用pywin32

    这是用于Win32 (pywin32)扩展的Python扩展库,它提供了对许多来自Python的Windows api的访问。

    4、使用老旧的版本 xlrd-0.6.1

    使用xlrd-0.6.1可以读取,没有异常抛出。直到我传入其他几个xls文件,出现Expected BOF record; found 0x4b50 错误,原因是xlrd-0.6.1不支持office2007

    参考资料:

    http://blog.sina.com.cn/s/blog_5e574c030101an5s.html

    https://blog.csdn.net/erlang_hell/article/details/51992928

    https://github.com/mhammond/pywin32

  • 相关阅读:
    SQL Server Audit监控触发器状态
    SQL Server 数据变更时间戳(timestamp)在复制中的运用
    SQL Server 更改跟踪(Chang Tracking)监控表数据
    SQL Server 变更数据捕获(CDC)监控表数据
    SQL Server 事件通知(Event notifications)
    SQL Server 堆表行存储大小(Record Size)
    SQL Server DDL触发器运用
    SQL Server 默认跟踪(Default Trace)
    SQL Server 创建数据库邮件
    SQL Server 跨网段(跨机房)FTP复制
  • 原文地址:https://www.cnblogs.com/Detector/p/8709362.html
Copyright © 2011-2022 走看看