问题
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