Python模塊學習之xlrd 讀取Excel時傳入formatting_info=True報錯:NotImplementedError: formatting_info=True not yet implemented


問題:xlrd讀取Excel時傳入 formatting_info=True 報錯

之前我們使用讀取xls文件的時候都是使用的xlrd庫,但是這個庫只能操作 .xls格式,對於后來的 .xlsx的版本支持不算太好。
比如說:當你使用xlrd來加載 xlsx文件的時候,在代碼中加入了

xlrd.open_workbook(filePath, formatting_info=True) 

該參數默認為False,這可以節省內存;當取值為True時,會讀取各種格式的信息。

但是在最新的 xlrd-0.8.0 版本中,讀取xlsx格式的Excel時,傳入formatting_info就會直接拋出異常:

Traceback (most recent call last):
  File "xxxxxxxx\test_read_excel_color.py", line 7, in <module>
    xlrd.open_workbook(r'./xxxxx.xlsx',formatting_info=True)
  File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 422, in open_workbook
    ragged_rows=ragged_rows,
  File "C:\Python27\lib\site-packages\xlrd\xlsx.py", line 751, in open_workbook_2007_xml
    raise NotImplementedError("formatting_info=True not yet implemented")
NotImplementedError: formatting_info=True not yet implemented

官網中 formatting_info 的解釋是:

> formatting_info –
The default is False, which saves memory. In this case, “Blank” cells, which are those with their own formatting information but no data, are treated as empty by ignoring the file’s BLANK and MULBLANK records. This cuts off any bottom or right “margin” of rows of empty or blank cells. Only cell_value() and cell_type() are available.

這個option使用與節約內存的。在這個情況下,空的單元格,存在格式信息但是沒有數據,將會被當成空來對待。這將會裁剪掉任何底部,右邊的“邊緣”空的表格。只有cell_value()和cell_type是有效的。
實際上在當關閉了這個option之后,當程序需要去加載cell中的顏色代碼的時候將會存在下面的問題。

Traceback (most recent call last):
  File "xxxxx\test_read_execel_color1.py", line 10, in <module>
    xf_idx  = xws1.cell_xf_index(0,0)
  File "C:\Python27\lib\site-packages\xlrd\sheet.py", line 420, in cell_xf_index
    self.req_fmt_info()
  File "C:\Python27\lib\site-packages\xlrd\sheet.py", line 1664, in req_fmt_info
    raise XLRDError("Feature requires open_workbook(..., formatting_info=True)")
XLRDError: Feature requires open_workbook(..., formatting_info=True)

還不知道里面是否還存在一些啥其他的問題。關閉了這個option之后,有些xlrd的代碼就不能這么寫了。

解決辦法

1、修改為xlsx為xls(推薦)

將.xlsx文件另存為.xls,然后再進行后續操作,親測有效,能正常保存Excel原有格式,不用修改代碼。(PS:直接將 .xlsx文件后綴修改為 .xls 是不可行的。)

2、改用 openpyxl

coding嘗試讀取文件,處理速度真的很慢...而且規則和宏全部丟失。

3、使用pywin32

這是用於Win32 (pywin32)擴展的Python的readme,它提供了對許多來自Python的Windows api的訪問。

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

使用xlrd-0.6.1可以讀取,沒有異常拋出。直到我傳入其他幾個xls文件,出現Expected BOF record; found 0x4b50 錯誤,原因是xlrd-0.6.1不支持office2007


免責聲明!

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



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