【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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM