C# Manipulate Excel Pivot Table

This article is transferred from the blog: http://www.cnblogs.com/Yesi/p/8715318.html

I. Overview

A Pivot Table is an interactive table that can perform certain calculations, such as sums and counts, dynamically change the layout of the pivot table, and rearrange row numbers, column headings, and page fields. When the layout is changed, the pivot table will also be updated according to the new layout, which can be said to be a powerful data analysis tool. Therefore, this article will introduce the operation example of Excel pivot table in C#. The example content mainly includes the following points:

1.  Create a pivot table

     (1) Create a data cache

     (2) Create a pivot table

     (3) Add row fields and column fields

     (4) Add value field

     (5) Set the style

2.   Set the row to collapse and expand

3.   Set fields in ascending and descending order

4.   Delete pivot table

2. Preparation tools



 PS : After installation, pay attention to refer to Spire.XLS.dll in the project and then perform code operations. The dll file is obtained in the Bin folder under the installation path.

3. Example operation

1. Create a pivot table

            //Create an instance of the Workbook class and load the Excel document
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("test.xlsx");

            // get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Create a cache for data that needs to be aggregated and analyzed
            CellRange dataRange = sheet.Range["A1:D10"];
            PivotCache cache = workbook.PivotCaches.Add(dataRange);

            //Create a pivot table using the cache and specify the name of the pivot table and its location in the worksheet
            PivotTable pivotTable = sheet.PivotTables.Add("PivotTable", sheet.Range["A12"], cache);

            //add row field
            var r1 = pivotTable.PivotFields["month"];
            r1.Axis = AxisTypes.Row;

            var r2 = pivotTable.PivotFields["Vendor"];
            r2.Axis = AxisTypes.Row;

            //Set the title of the row field
            pivotTable.Options.RowHeaderCaption = "Month";

            //add column field
            var col1 = pivotTable.PivotFields["Product"];
            col1.Axis = AxisTypes.Column;          

            //Set the title of the column field
            pivotTable.Options.ColumnHeaderCaption = "产品";

            //add value field
            pivotTable.DataFields.Add(pivotTable.PivotFields["Total Yield"], "Sum Item:Total Yield", SubtotalTypes.Sum);

            //Set the style of the pivot table (Spire.XLS supports more than 80 built-in pivot table styles in Excel)
            pivotTable.BuiltInStyle = PivotBuiltInStyles.PivotStyleDark13;

            // save and open the document
            workbook.SaveToFile("PivotTable.xlsx", ExcelVersion.Version2013);
            System.Diagnostics.Process.Start("PivotTable.xlsx");

 Test Results:



 

2. Set the row to collapse and expand

            //Create a Workbook class object and load the Excel document  
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("PivotTable.xlsx");

            // get the pivot table  
            XlsPivotTable pivotTable = workbook.Worksheets[0].PivotTables[0] as XlsPivotTable;

            //calculate data  
            pivotTable.CalculateData();

            //Expand the details of "2" under the "Month" field  
            (pivotTable.PivotFields["月份"] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotField).HideItemDetail("2", false);
            // Collapse the details of "3" under the "Month" field
            (pivotTable.PivotFields["月份"] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotField).HideItemDetail("3", true);

            // save and open the document  
            workbook.SaveToFile("Collapse, expand row.xlsx", ExcelVersion.Version2013);
            System.Diagnostics.Process.Start("Collapse, expand line.xlsx");

 Test Results:



 

3. Set field sorting

Three different types of sorting are supported here, and the corresponding sorting type can be selected as needed.



 

            //Create a Workbook class object and load the Excel document  
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("PivotTable.xlsx");

            // get the pivot table  
            Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable pivotTable = workbook.Worksheets[0].PivotTables[0] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable;

            // sort the specified field in ascending order  
            pivotTable.PivotFields[2].SortType = PivotFieldSortType.Ascending;

            // save and open the document  
            workbook.SaveToFile("升序.xlsx", ExcelVersion.Version2013);
            System.Diagnostics.Process.Start("Ascending.xlsx");

 Test Results



 

4. Delete pivot table

There are two ways to delete a pivot table:

  •  Delete based on pivot table name
  •  Delete based on pivot table index
            //Create a workbook and load the Excel document
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("PivotTable.xlsx");

            //delete the pivot table named "PivotTable" on the first worksheet  
            workbook.Worksheets[0].PivotTables.Remove("PivotTable");

            //Delete the first pivot table with index 0 on the first worksheet  
            //workbook.Worksheets[0].PivotTables.RemoveAt(0);  

            // save the document  
            workbook.SaveToFile("Delete PivotTable.xlsx", ExcelVersion.Version2013);

 Test Results:


Guess you like

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