Python Xlsxwriter 简明教程

Python XlsxWriter - Hide/Protect Worksheet

工作表对象 hide() 方法使工作表消失,直到通过 Excel 菜单将其取消隐藏。

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

在以下工作表中,有三个工作表,其中 sheet2 已隐藏。

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

您不能隐藏 “ active ” 工作表,它通常是第一个工作表,因为这会导致 Excel error 。因此,为了隐藏第一个工作表,您需要激活另一个工作表。

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

要隐藏工作表中的特定行或列,请在 set_row()set_column() 方法中将隐藏参数设置为 1。以下语句隐藏活动工作表中的 C、D 和 E 列。

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

执行上述代码后,C、D 和 E 列在下方工作表中不可见 −

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

hide column

同理,借助 set_row() 方法,我们可以隐藏带有 hidden 参数的行。

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