Python3でパスワードの設定されているExcelファイルを扱う方法

Pythonでパスワードで保護されたExcelファイルを扱うには msoffcrypt が便利です。

python -m pip install msoffcrypto-tool

# モジュールを読み込む
import openpyxl
import msoffcrypto

# パスワード
PASSWORD = "mypassword"
# 暗号化されたファイル
encrypted_file_name = "パスワード付きファイル.xlsx"
# 復号化して保存するファイル
decrypted_file_name = "パスワード解除後.xlsx"

# 暗号化ファイルを開く
f = open(encrypted_file_name, "rb")
encrypted_file = msoffcrypto.OfficeFile(f)

# 復号化のパスワードを設定する
encrypted_file.load_key(password=PASSWORD)

# 復号化したファイルを別のファイルに保存する
decrypted_file = open(decrypted_file_name, "wb")
encrypted_file.decrypt(decrypted_file)

book = openpyxl.load_workbook(decrypted_file_name)
sheet = book.active

# A1にアクセス
cell_A1 = sheet["A1"]
print(cell_A1.value)

暗号化されたExcelファイルをPythonで扱う

手順は難しくありません。

まず最初にopen()でファイルを開きます。このときバイナリモードで開きます。ファイルを開いたら msoffcrypt で扱うためにオブジェクトを作成しておきます(encrypted_file)。

# 暗号化ファイルを開く 
f = open(encrypted_file_name, "rb") 
encrypted_file = msoffcrypto.OfficeFile(f)

復号化は次のようにしておこないます。まず encrypted_file.load_key(password=PASSWORD) で復号化するためのパスワードを設定し、encrypted_file.decrypt(decrypted_file) で復号化して別名で保存しています。

# 復号化のパスワードを設定する
encrypted_file.load_key(password=PASSWORD)

# 復号化したファイルを別のファイルに保存する
decrypted_file = open(decrypted_file_name, "wb")
encrypted_file.decrypt(decrypted_file)

その後は通常のExcelと同様にPythonで扱う亊ができます。

この記事は役に立ちましたか?

もし参考になりましたら、下記のボタンで教えてください。

関連記事

コメント

この記事へのコメントはありません。