C# set Excel data multi-level grouping

I. Overview

In Excel, if the data with multi-level details can be grouped and displayed, the overall structure of the data table can be clearly displayed, so that the entire document has a certain sense of hierarchy. Set to show or hide the detailed information under the classified data as required, which not only facilitates data viewing and management, but also makes the document more aesthetically pleasing. So, how to create multi-level grouping display of Excel data in C#? It will be explained in detail below.

 

Second, the use of tools

Free Spire.XLS for .NET

 

3. Implementation steps

step1 Create a Wordbook class object and get the first worksheet

 

Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];

 

 

step2 write data to the cell

 

sheet.Range["A1"].Value = "Company Department";
sheet.Range["A3"].Value = "综合部";
sheet.Range["A4"].Value = "行政";
sheet.Range["A5"].Value = "人事";
sheet.Range["A6"].Value = "市场部";
sheet.Range["A7"].Value = "业务部";
sheet.Range["A8"].Value = "客服部";
sheet.Range["A9"].Value = "技术部";
sheet.Range["A10"].Value = "Technology Development";
sheet.Range["A11"].Value = "Technical Support";
sheet.Range["A12"].Value = "Pre-sales support";
sheet.Range["A13"].Value = "After-sales support";

 

 

step3 Set the IsSummaryRowBelow property to false, that is, the summary row is displayed above the detail row

 

sheet.PageSetup.IsSummaryRowBelow = false;

 

 

step4 Select rows for grouping. The parameter false means to expand the current group. If you want to hide it, set it to true

 

//Select rows for first-level grouping
sheet.GroupByRows(2, 13, false);
//Select rows for secondary grouping
sheet.GroupByRows(4,5 , false);
sheet.GroupByRows(7, 8, false);
sheet.GroupByRows(10,13 , false);
//Select rows for three-level grouping
sheet.GroupByRows(12,13, true);

 

 

step5 Define a CellStyle object, set and apply the format to the font in the cell

CellStyle style = workbook.Styles.Add("style");
style.Font.IsBold = true;
style.Color = Color.LawnGreen;
sheet.Range["A1"].CellStyleName = style.Name;
sheet.Range["A3"].CellStyleName = style.Name;
sheet.Range["A6"].CellStyleName = style.Name;
sheet.Range["A9"].CellStyleName = style.Name;

 

step6 Set the area border style

sheet.Range["A4:A5"].BorderAround(LineStyleType.Thin);
sheet.Range["A4:A5"].BorderInside(LineStyleType.Thin);
sheet.Range["A7:A8"].BorderAround(LineStyleType.Thin);
sheet.Range["A7:A8"].BorderInside(LineStyleType.Thin);
sheet.Range["A10:A13"].BorderAround(LineStyleType.Thin);
sheet.Range["A10:A13"].BorderInside(LineStyleType.Thin);

 

step7 save the document

workbook.SaveToFile("output.xlsx", ExcelVersion.Version2013);

 

Run the program to generate the documentation (you can view the generated documentation in the bin>Debug folder under the project folder)

 


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325979539&siteId=291194637