简体   繁体   中英

No data showing when programmatically creating Excel pivot table using C# and adding fields to row labels

I'm trying to programmatically build an excel pivot table based on database table. I'm able to build a spreadsheet, and all of the database table columns are available as fields. But adding fields to the Row Labels box is not showing any data.

If I look in the column filters it has correct values there, and if I add a field to the Values box, spreadsheet updates with correct data. So I know it connects to database and can get data out.

I can build a pivot table by hand and adding fields to row labels box works fine, I'm trying to do the same in code. Any ideas on why I can't see any data?

Here is the code I'm using:

        var excelApp = new Application();
        excelApp.CellDragAndDrop = false;
        excelApp.DisplayAlerts = true;
        Workbook workBook = excelApp.Workbooks.Add(Type.Missing);

        Worksheet worksheet = workBook.Worksheets.Add();
        worksheet.Name = "Test";

        PivotCache pivotCache = workBook.PivotCaches().Add(XlPivotTableSourceType.xlExternal, Type.Missing);

        pivotCache.Connection = myConnectionString;
        pivotCache.MaintainConnection = true;
        pivotCache.CommandText = "SomeTable";
        pivotCache.CommandType = XlCmdType.xlCmdTable;

        PivotTables pivotTables = worksheet.PivotTables();
        PivotTable pivotTable = pivotTables.Add(pivotCache, excelApp.ActiveCell, "TestingPivot", true, Type.Missing);

        excelApp.Visible = true;

Thank you for your help!

I think I got it to work. Instead of

PivotCache pivotCache = workBook.PivotCaches().Add(XlPivotTableSourceType.xlExternal, Type.Missing);

Use this:

PivotCache pivotCache = workBook.PivotCaches().Create(XlPivotTableSourceType.xlExternal, Type.Missing, Type.Missing);

This solved my problem for me.

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