English 中文(简体)
Python XlsxWriter - Hide/Protect Worksheet
  • 时间:2024-12-22

Python XlsxWriter - Hide/Protect Worksheet


Previous Page Next Page  

The worksheet object s hide() method makes the worksheet disappear till it is unhidden through Excel menu.

In the following worksheet, there are three sheets, of which sheet2 is hidden.


sheet1 = workbook.add_worksheet()
sheet2 = workbook.add_worksheet()
sheet3 = workbook.add_worksheet()

# Hide Sheet2. It won t be visible until it is unhidden in Excel.
worksheet2.hide()

It will create the following worksheet −

Hide

You can t hide the "active" worksheet, which generally is the first worksheet, since this would cause an Excel error. So, in order to hide the first sheet, you will need to activate another worksheet.


sheet2.activate()
sheet1.hide()

Hide Specific Rows or Columns

To hide specific rows or columns in a worksheet, set hidden parameter to 1 in set_row() or set_column() method. The following statement hides the columns C, D and E in the active worksheet.


worksheet.set_column( C:E , None, None, { hidden : 1})

Example

Consider the following program −


import xlsxwriter

wb = xlsxwriter.Workbook( hello.xlsx )
worksheet = wb.add_worksheet()
format1=wb.add_format({ bg_color : #D9D9D9 ,  bold :True})

for col in range(0, 15):
   worksheet.write(0, col, col+1, format1)
   
for row in range(1, 51):
   for col in range(0,15):
      if col==0:
         worksheet.write(row,col,(col+1)*(row + 1), format1)
      else:
         worksheet.write(row,col,(col+1)*(row + 1))
worksheet.set_column( C:E , None, None, { hidden : 1})

wb.close()

Output

As a result of executing the above code, the columns C, D and E are not visible in the worksheet below −

Hide Column

Similarly, we can hide rows with set_row() method with the help of hidden parameter.


for row in range(5, 7):
   worksheet.set_row(row, None, None, { hidden :1})

Here is the result −

Hide Row Advertisements