Refreshing an Excel Pivot table from C#

前端 未结 3 613
旧巷少年郎
旧巷少年郎 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条回答
  •  梦毁少年i
    2021-01-14 05:39

    private void RefreshSheets(string filePath)
        {
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbooks xlWorkbooks = xlApp.Workbooks;
            Excel.Workbook xlWorkbook = xlWorkbooks.Open(filePath);
    
            foreach (Excel.Worksheet xlworksheet in xlWorkbook.Worksheets)
            {
                Excel.PivotTables pivotTbls = (Excel.PivotTables)xlworksheet.PivotTables(Type.Missing);
                if (pivotTbls.Count > 0)
                {
                    for (int i = 1; i <= pivotTbls.Count; j++)
                    {
                        pivotTbls.Item(i).RefreshTable();
                    }
                }
            }
            xlWorkbook.Save();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            xlWorkbook.Close(0);
            Marshal.ReleaseComObject(xlWorkbook);
            Marshal.ReleaseComObject(xlWorkbooks);
            xlApp.Quit();
            Marshal.ReleaseComObject(xlApp);
        }
    

    Add using Excel = Microsoft.Office.Interop.Excel; in using

提交回复
热议问题