LoginSignup
0
5

More than 1 year has passed since last update.

PythonでExcelファイルのパスワードを解除

Last updated at Posted at 2023-03-31

概要

パスワード付きのExcelファイルをパスワードなしに保存するコードのメモです。
勿論パスワードを知っている前提の話です。
PHP言語でパスワード付きのExcelファイルを読み込みができないため、
アップロードされたExcelファイルをサーバ上でPython処理でパスワードを解除して
保存する処理です。

Python環境

下記の環境で試したコードになります。

OS : redhat 8.5
Python : python3.X
Library : msoffcrypto-tool

事前インストール

次の順番でパッケージをインストールします。
①sudo yum install python2
②sudo yum install python3
③sudo python3 -m pip install --upgrade pip
→④番のインストールため、事前にpipのバージョンアップが必要でした。
④pip3 install msoffcrypto-tool

Pythonコード

次のコードを書いてcrack.pyに保存します。

import os
import msoffcrypto

def xl_pw_decript(raw_path, new_path):

    xlfile_list = os.listdir(raw_path)
    print(xlfile_list)

    for xlfile in xlfile_list:
        encrypted = open(raw_path + xlfile, 'rb')
        file = msoffcrypto.OfficeFile(encrypted)
        file.load_key(password='Passw0rd')

        with open(new_path + xlfile, 'wb') as f:
            file.decrypt(f)
            print("unlock file make")

        encrypted.close()

raw_path = "./excel/"
new_path = "./test/"
xl_pw_decript(raw_path, new_path)

パスワード付きのExcelを作成

下記のサイト参照してパスワードを設定します。
https://www.passfab.jp/excel/removal-and-setting-of-excel-password.html

Pythonコード実行結果

次のコマンドで作成したコードを実行します。
警告のようなメッセージは表示されますが、動作は問題なくパスワードなしのファイルが作成できました。

[redhat@localhost ~]$ python3
Python 3.6.8 (default, Sep  9 2021, 07:49:02)
[GCC 8.5.0 20210514 (Red Hat 8.5.0-3)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

[redhat@localhost ~]$ python3 crack.py
['task_password.xlsx']
/usr/local/lib/python3.6/site-packages/msoffcrypto/method/ecma376_agile.py:8: CryptographyDeprecationWarning: Python 3.6 is no longer supported by the Python core team. Therefore, support for it is deprecated in cryptography. The next release of cryptography will remove support for Python 3.6.
  from cryptography.hazmat.backends import default_backend
unlock file make
[redhat@localhost ~]$ ls test/
task_password.xlsx

終わりに

PHPでパスワード付きのExcelファイルの取り込みができないので、
今回のようにアップロードされたExcelファイルをサーバ側でパスワード解除版を保存してから
データ処理するのも良いと思いまして作成してみました。
Pythonでパスワードを指定してExcelファイル保存もできると良いですね。

0
5
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
5