Openpyxl and Hidden/Unhidden Excel Worksheets

时光毁灭记忆、已成空白 提交于 2019-12-04 20:38:23

问题


I have the following code that reads data from a tab-delimited text file and then writes it to a specified worksheet within an existing Excel workbook. The variables "workbook", "write_sheet", and "text_file" are input by the user

tab_reader = csv.reader(text_file, delimiter='\t')
xls_book = openpyxl.load_workbook(filename=workbook)
sheet_names = xls_book.get_sheet_names()
xls_sheet = xls_book.get_sheet_by_name(write_sheet)
for row_index, row in enumerate(tab_reader):
        number = 0
        col_number = first_col
        while number < num_cols:
                cell_tmp = xls_sheet.cell(row = row_index, column = col_number)
                cell_tmp.value = row[number]
                number += 1
                col_number += 1
xls_book.save(workbook)

However when I run this code on a preexisting "workbook" in which "worksheet" is a hidden tab, the output unhides the tab. I think the reason is because openpyxl is not modifying the file but creating a new file entirely. Is there an easy way to tell python to check if the worksheet is hidden and then output a hidden or unhidden sheet based on whether or not the condition is satisfied?

Thanks!


回答1:


We currently don't support hiding worksheets in openpyxl so this is just ignored when reading the file and, therefore, lost when saving it. I don't think it should be too hard to add it. Please submit a feature request on Bitbucket.

[UPDATE]

The feature is now available:

ws.sheet_state = 'hidden'

Or actually xls_sheet.sheet_state = 'hidden' in your particular case.




回答2:


Charlie Clark's comment is correct:

ws.sheet_state = 'hidden'

this works for me.



来源:https://stackoverflow.com/questions/23157643/openpyxl-and-hidden-unhidden-excel-worksheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!