Skip to content

xlrd からの移行

xlrd はレガシー .xls(Excel 97–2003)ファイル読み取りの標準 Python ライブラリでした。2.0(2020)で .xls サポートを打ち切り、移行を推奨しています。コミュニティの回避策 — xlrd<2.0 をピン留め、LibreOffice にシェルアウト、python-calamine に切り替え — にはそれぞれ注意点があります。

Office Oxide は .xls を直接読み取り、xlrd の最後の .xls 対応リリースより 13 倍高速 で、パス率も高いです。おまけとして .xls.xlsx の変換を 1 行で行えます。

いつ移行するか

以下のいずれかが当てはまるなら切り替えを:

  • まだ xlrd<2.0 上にいて、メンテナンスされているライブラリが欲しい
  • 1 つのライブラリで .xls.xlsx の両方が必要
  • コーパスを一度 .xlsx に移行して、レガシー形式と縁を切りたい
  • .doc.ppt.docx.pptx も必要 — 同じインストールで対応

インストール

pip uninstall xlrd
pip install office-oxide

並べて比較するチートシート

.xls を開く

xlrd

import xlrd

book = xlrd.open_workbook("legacy.xls")
sheet = book.sheet_by_index(0)

office_oxide

from office_oxide import Document

with Document.open("legacy.xls") as doc:
    xls = doc.as_xls()
    sheet = xls.sheets()[0]

セルをイテレーション

xlrd

for row in range(sheet.nrows):
    for col in range(sheet.ncols):
        print(sheet.cell_value(row, col))

office_oxide

for cell in sheet.cells():
    print(cell.address(), cell.value())

すべてのセルをテーブルとして読む(最も一般的なケース)

xlrd

import xlrd

book = xlrd.open_workbook("legacy.xls")
sheet = book.sheet_by_index(0)
rows = [
    [sheet.cell_value(r, c) for c in range(sheet.ncols)]
    for r in range(sheet.nrows)
]

office_oxide

from office_oxide import Document

with Document.open("legacy.xls") as doc:
    ir = doc.to_ir()

# 最初のシート → 最初のセクション → 最初のテーブル
table = next(el for el in ir["sections"][0]["elements"] if el["kind"] == "Table")
rows = table["rows"]

シート名

xlrd

book = xlrd.open_workbook("legacy.xls")
print(book.sheet_names())

office_oxide

with Document.open("legacy.xls") as doc:
    print([s.name() for s in doc.as_xls().sheets()])

.xls → .xlsx を 1 行で変換

下流のツールがすでに .xlsx を話せるなら、もっともクリーンな移行パスはコーパスを一度変換して二度と .xls に触れないことです:

from office_oxide import Document

with Document.open("legacy.xls") as doc:
    doc.save_as("modern.xlsx")

ディレクトリ全体の場合:

from pathlib import Path
from office_oxide import Document

for src in Path("legacy").rglob("*.xls"):
    dst = src.with_suffix(".xlsx")
    with Document.open(src) as doc:
        doc.save_as(dst)

パフォーマンス

ライブラリ .xls 平均 p99 通過率
office_oxide 2.8 ms 75 ms 99.2%
python-calamine 9.0 ms 96 ms 90.7%
xlrd 36.6 ms 503 ms 93.1%

Office Oxide は xlrd より 13 倍高速で、パス率は 6.1 ポイント高い。

失われるもの

xlrd の数式表現、定義名、共有数式キャッシュは IR を通して公開されません。キャッシュされた数式 結果 は残ります — それがほとんどの下流ツールが実際に必要とするものです。数式表現にはフォーマット固有の xls モジュールに降りるか、.xlsx に変換して xlsx を使ってください。

関連項目