How to read outline levels using Python `openpyxl`?

Viewed 552

My organization has a clean export for bills of materials (BOM). I would like to automatically parse the excel file to check the BOM for certain attributes.

At the moment, I'm using Python with openpyxl.

I can read the excel workbook and worksheet just fine, but I cannot seem to find the attribute that contains the "outline level" of each row (I fully concede that I may be using the wrong terminology... another term candidate might be "group").

When I look at my excel file using excel, I see this at the left of the screen:

excel image snapshot

I would like to extract the 1 2 3 4 5 from each of the rows and to tell what grouping they were in.

My initial code is:

from pathlib import Path 
import openpyxl as xl


path = Path('<path-to-my-file>.xlsx')

wb = xl.load_workbook(filename=path)
sh = wb.worksheets[0]

# ... would like to put outline level reading code here

From reading other questions, I suspect that I need to look at the row_dimension.group method of the worksheet, but I can't seem to get a handle on the syntax or the exact attribute that I'm looking for.

2 Answers

Thanks for the post. I was struggling with the same problem and seing your post gave me an idea!

I overcome it with the following code:

from pathlib import Path 
import openpyxl as xl

path = Path('<path-to-my-file>.xlsx')

wb = xl.load_workbook(filename=path)
sh = wb.worksheets[0]

for row in sorted(sheet.row_dimensions):
    outline1=sheet.dimensions[row].outlineLevel
    outline2=sheet.dimensions[row].outline_level
    print(row,sheet.dimensions[row], outline1, outline2 )

Maybe you can use the following code to gather individual row outline levels as an integer. I use a similar code to find maximum outline level in a sheet with some more lines.

for index in range(ws.min_row, ws.max_row):
    row_level = ws.row_dimensions[index].outline_level + 1

In here row level variable is the outline level, you may use as required. But please double check +1, if I remember correctly, to get true level, you need to increase variable by one.

Related