简体   繁体   中英

Create pivot table without the base table in Epplus (C#)

Can is possibility create Excel document without placed inside spreedsheet the base table? Or at least that base table was in other worksheet than pivot table.

Currently I create DataColumn, after add row and...

ExcelWorksheet worksheet = pkg.Workbook.Worksheets.Add("Table");
            worksheet.Cells["A1"].LoadFromDataTable(table, true);
var pivotTable = worksheet.PivotTables.Add(worksheet.Cells["H14"], 

worksheet.Cells[rangePivotTable], "pivTable");
pivotTable.RowFields.Add(pivotTable.Fields["Grid"]);
.
.
.

It seems that EPPlus PivotTable can be created only from the data that is already present in the workbook; so you have to place source table into the spreadsheet.

Good news is that you can easily have pivot table and base table in the different worksheets:

var wsPvt = pkg.Workbook.Worksheets.Add( "Pivot Table" );
var wsData = pkg.Workbook.Worksheets.Add( "Source Data" );

var rangePivotTable = wsData.Cells["A1"].LoadFromDataTable( tbl, true );

var pivotTable = wsPvt.PivotTables.Add(
        ws.Cells[1,1], 
        rangePivotTable, "pvtTable");

I assume that you don't want to place base table into spreadsheet because it is either rather big or just contain sensitive details. In this case you may aggregate base table with C# code (group it by columns that used for pivot table rows and columns) and use grouped result as base table for Excel Pivot Table. Aggregation may be simply performed with PivotData library -- let me know if you're interested in this way and need more explanations (I'm an author of this library).

Absolutely! Just set the data source of the pivot table using PivotTable.SourceData to specify a connection string.

https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.pivottable.sourcedata.aspx

A little different way to do it, that works for me, is as follows:

var dataRange = rawDataWorksheet.Cells[rawDataWorksheet.Dimension.Address];
var pivotTable =
    pivotTableWorksheet.PivotTables.Add(pivotTableWorksheet.Cells["A6"]
        dataRange, "PivotTable");

"rawDataWorksheet" is the sheet that contains the source data; "pivotTableWorksheet" is the sheet on which you want to plop the PivotTable. In the code above, it starts at the intersection of column A (1) and row 6, but you could use another target cell, of course.

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