1
1

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 1 year has passed since last update.

PythonでExcelファイルをパスワード保護する

Last updated at Posted at 2022-08-16

PythonでExcelファイルにパスワードを付けたいと思って調べても情報が少なかったので共有します。
今回はWindows環境を想定しています。

protect_excel_with_password.py

from win32com.client.gencache import EnsureDispatch
from openpyxl import load_workbook
from pathlib import PurePath

def set_wb_password_with_win32(file_dir_path, password):
    xl_file = EnsureDispatch("Excel.Application")
    wb = xl_file.Workbooks.Open(file_dir_path)
    xl_file.DisplayAlerts = False
    wb.Visiable = False
    wb.SaveAs(file_dir_path, Password=password)
    wb.Close()
    xl_file.Quit()

if __name__ == "__main__":
    dir_path = "DIRECTORY_PATH"
    file_name = "FILE_NAME"
    file_path = PurePath(dir_path, file_name)
    password = "PASSWORD"
    print(file_path)
    set_wb_password_with_win32(str(file_path), password)
    print("Finished")

"DIRECTORY_PATH", "FILE_NAME", "PASSWORD"の3カ所を任意の値に変更します。

後はコマンドプロンプトやPowerShellなどから下記のコマンドを実行すると処理ができると思います。

python protect_excel_with_password.py

この記事の内容を試してみて動いた場合や、動かなかった場合、または動かなかったけれども修正して動いた場合など、コメントをいただけますと幸いです。

こちらの記事は下記の動画を元に作成しました。

1
1
5

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?