Search code examples
pythonexcelopenpyxlwin32comvba

Split excel file into multiple by excel groups


By groups I mean this expandable things:

pic1

When pressing on them we can expand some rows, in this particular case I need to extract rows to different data locations (in whatever, list of rows/better - other excel files), grouped by 1st, hm, group:

pic2

So that, for example in this case:

file1.xlsx will be include all rows from 6 to 572

file2.xlsx will be include rows from 573 to 627

and so on.

How to perform this? It can be VBA script, but better with some python library like openpyxl or win32com.client


Solution

  • # -*- coding: utf-8 -*-
    import openpyxl
    
    wb = openpyxl.load_workbook(r'path_to_xlsx_file')
    ws = wb.active
    range_string = ws.calculate_dimension()
    print(range_string)
    for row_index, row in enumerate(ws.iter_rows(range_string=range_string)):
        print(ws.row_dimensions[row_index].index,  # just for the great LULZ
              ws.row_dimensions[row_index].outline_level,  # THAT what I was looking for!
              ws.row_dimensions[row_index].hidden,  # couple other helpful parameters
              ws.row_dimensions[row_index].collapsed,
              ws.row_dimensions[row_index].height)