Set Password for excel file using Python

10,175

Can you try using the below code,

from openpyxl import Workbook
wb = Workbook()

ws=wb.worksheets[0]
ws.protection.set_password('test')
wb.save('sample.xlsx')
Share:
10,175

Related videos on Youtube

Sanjo
Author by

Sanjo

A guy who likes to solve problems and travel a lot.

Updated on May 25, 2022

Comments

  • Sanjo
    Sanjo almost 2 years

    I am trying to set password for excel file generated using openpyxl. I went through openpyxl. Openpyxl has a workbook protection functionality, but it does not support whole workbook lock using password as it does in MS Excel. I also looked into xlsxwriter, xlrd, xlwt.

    Is there any way in python which i can set password for an excel file ?

    Thanks in advance.

    • AmyOakes
      AmyOakes over 6 years
      Try here.. Think this answers your question. link
    • Sanjo
      Sanjo over 6 years
      I have seen this link, Openpyxl has no functionality to password protect a workbook. but that question does not provide a clear answer whether any python library other than Openpyxl can be used to lock an excel file or whole excel workbook.
    • AmyOakes
      AmyOakes over 6 years
      it kind of does, basically i get the impression that you cant do it, check out this one link If you follow @gar link to the bitbucket page you mind find some more help there.
    • John Y
      John Y almost 6 years
      @amyoakes - That did get implemented, but it still doesn't provide the functionality that I think Sanjo meant, which is to make it so that the workbook cannot even be opened without the password. The feature that got implemented was protection of the workbook structure, which simply means you cannot add, move, delete, hide, or unhide sheets (without disabling the protection, which is rather easy to do). You can still open the workbook normally.
    • John Y
      John Y almost 6 years
      See my answer on a similar (or perhaps duplicate) question.
  • Sanjo
    Sanjo over 6 years
    Unfortunately code you mentioned only provide worksheet protection for the selected worksheet, not for the whole workbook or excel file in Openpyxl.
  • sujit
    sujit over 6 years
    Can you try changing the index of worksheets
  • Hietsh Kumar
    Hietsh Kumar about 4 years
    please test your code before answer
  • Forrest Hu
    Forrest Hu over 2 years
    don't think the password protection work.