0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Excel 入出力で文字列IDが数値化されていないか openpyxl で確認するメモ

0
Posted at

はじめに

業務で、Excel 経由後に文字列IDが数値として読めるケースがあった。

このメモでは、作成済み xlsx を openpyxl で読み込み、文字列ID列のセルが「数値 + 科学表記フォーマット」になっていないかを確認する。例には説明用の 12E3 を使う。

確認するExcelセルの状態

次の 2 つを同時に満たすセルを確認する。

  • cell.value が数値として読める
  • cell.number_format に科学表記の形式が付いている

Excel 上の見た目だけでは、セルの中の値が文字列として保持されているのか、数値として保存されているのかが分かりにくい。作成済みの xlsx を openpyxl で読み込み、値そのものと表示形式を分けて見る。

openpyxl で確認する値

cell.value、Python 型、cell.number_format の 3 つを確認する。

cell = ws.cell(row=row_index, column=code_col_index)

print(cell.value)
print(type(cell.value).__name__)
print(cell.number_format)

検出例

検出条件は「対象列が文字列ID列であること」を前提に、値が数値で、表示形式が科学表記であることに絞る。

  • cell.value が数値として読める
  • cell.number_format が科学表記を示している
from numbers import Number


def looks_converted_code_cell(cell) -> bool:
    fmt = (cell.number_format or "").upper()
    return (
        isinstance(cell.value, Number)
        and not isinstance(cell.value, bool)
        and ("E+" in fmt or "E-" in fmt)
    )

Numberintfloat をまとめて判定するために使っている。Python では bool も数値型として扱われるため、True / False は判定から外している。

検証用データでの確認

実データではなく説明用の xlsx に次の 3 種類のセルを作成して検証した。

  • 文字列として保持された値
  • 数値として保持され、科学表記フォーマットが付いた値
  • 数値として保持されているが、科学表記フォーマットではない値

そのブックを openpyxl で読み戻し、上の検出条件を当てた結果が次の表。

12E3 は説明用の文字列ID。数値として保存されていれば、12000 のような数値として読まれる。

openpyxl で読んだ cell.value Python 型 cell.number_format この条件での判定
12E3 str @ 対象外
12000 int 0.00E+00 対象
12000 int General 対象外

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?