4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

パスワード付きExcelをPythonで読み込む方法(Linux対応)

Posted at

#はじめに
xlwingsがLinuxだと非対応だったのでOSに依存しない方法がないかと模索した結果です

#事前準備
今回利用するライブラリです

import pandas as pd
import tempfile
import msoffcrypto
from pathlib import Path

msoffcryptoはインストール時は名称が違います

pip install msoffcrypto-tool

#サンプルコード

下記の場合を想定しています
・あるディレクトリ(input/)配下の全てのxlsxファイルの対象のシートをcsv出力
・パスワードが全て同じ(hogehoge)
・読み込みたいシート名が全て同じ(Sheet1)

import pandas as pd
import tempfile
import msoffcrypto
from pathlib import Path

file_dir = Path(r'data/')
password = 'hogehoge'
sheet_name = 'Sheet1'

for file in file_dir.glob("*.xlsx"):
    with file.open("rb") as f,tempfile.TemporaryFile() as tf:
        office_file = msoffcrypto.OfficeFile(f)
        office_file.load_key(password=password)
        office_file.decrypt(tf)
        df = pd.read_excel(tf,sheet_name=sheet_name)
    df.to_csv('output/' + file.name.replace('','xlsx') + '.csv',index=False)
4
7
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
4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?