Refreshing an Excel Pivot table from C#

前端 未结 3 629
旧巷少年郎
旧巷少年郎 2021-01-14 04:57

I am trying to refresh a pivot table in an Excel sheet and get the following exception:

Item method in the PivotTables class failed

Heres t

3条回答
  •  生来不讨喜
    2021-01-14 05:36

    This will help you it's working.

    Microsoft.Office.Interop.Excel.Application oXL;
    Microsoft.Office.Interop.Excel.Workbook mWorkBook;
    Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
            
    oXL = new Microsoft.Office.Interop.Excel.Application();
    oXL.Visible = true;
    oXL.DisplayAlerts = false;
    mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
    //Get all the sheets in the workbook
    mWorkSheets = mWorkBook.Worksheets;
    foreach (Microsoft.Office.Interop.Excel.Worksheet pivotSheet in mWorkSheets)
    {
        Microsoft.Office.Interop.Excel.PivotTables pivotTables = pivotSheet.PivotTables();
        int pivotTablesCount = pivotTables.Count;
        if (pivotTablesCount > 0)
        {
            for (int i = 1; i <= pivotTablesCount; i++)
            {
                pivotTables.Item(i).RefreshTable(); //The Item method throws an exception
            }
        }
    }     
     
    

提交回复
热议问题