简体   繁体   中英

Grouping lines with XlsxWriter

I'm writing an Excel file with Python and XlsxWriter in which I'd like to group elements in 2 levels. Several 'boards' contain elements grouped by 'list'. I'd like to group all elements of the same 'list' and all the elements of the 'board' together.

After many attempts I did not succeed in getting the following result:

预期结果的Excel示例

Can someone help me understand how the function below works:

worksheet.set_row(1, None, None, {'level': 1})

I've followed the example given in the documentation but I don't know what level to set on each line to have 2 grouping levels working as expected.

You can do it like the following which matches the first part of your screenshot.

import xlsxwriter

workbook = xlsxwriter.Workbook('outline.xlsx')
worksheet = workbook.add_worksheet()

worksheet.set_row(1, None, None, {'level': 2})
worksheet.set_row(2, None, None, {'level': 1})
worksheet.set_row(3, None, None, {'level': 2})
worksheet.set_row(4, None, None, {'level': 2})
worksheet.set_row(5, None, None, {'level': 2})
worksheet.set_row(6, None, None, {'level': 1})

worksheet.set_row(8, None, None, {'level': 2})
worksheet.set_row(9, None, None, {'level': 1})

worksheet.set_row(12, None, None, {'level': 2})
worksheet.set_row(13, None, None, {'level': 2})
worksheet.set_row(14, None, None, {'level': 2})
worksheet.set_row(15, None, None, {'level': 2})
worksheet.set_row(16, None, None, {'level': 1})
worksheet.set_row(17, None, None, {'level': 1})
worksheet.set_row(18, None, None, {'level': 2})
worksheet.set_row(19, None, None, {'level': 2})
worksheet.set_row(20, None, None, {'level': 2})
worksheet.set_row(21, None, None, {'level': 1})

workbook.close()

Output:

在此处输入图片说明

The trick is to fill in the level 1 rows where you need a contiguous grouping. Note that in the example there are values from row 1-6, 8-9 and 12-21 (zero indexed).

Update : Added row 12-23 grouping in response to the follow-on question below. Updated image as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM