从C#刷新Excel数据透视表

时间:2010-11-10 06:46:54

标签: c# .net

我正在尝试刷新Excel工作表中的数据透视表并获得以下异常:

Item method in the PivotTables class failed

下面是代码:

pivotSheet.Activate();
Microsoft.Office.Interop.Excel.PivotTables pivotTables = 
        (Microsoft.Office.Interop.Excel.PivotTables)pivotSheet.PivotTables(missing);
int pivotTablesCount = pivotTables.Count;  
    if (pivotTablesCount > 0)
    {
        for (int i = 0; i <= pivotTablesCount; i++)
        {
            pivotTables.Item(i).RefreshTable(); //The Item method throws an exception
        }
    }

有什么想法吗?

3 个答案:

答案 0 :(得分:8)

假设索引从零开始,您将使用循环超出集合。

尝试:

for (int i = 0; i < pivotTablesCount; i++)

如果不起作用,Excel可能会开始索引为1而不是0。

尝试:

for (int i = 1; i <= pivotTablesCount; i++)

答案 1 :(得分:2)

这将有助于您的工作。

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
        }
    }
}     

答案 2 :(得分:0)

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);
    }

使用Excel添加= Microsoft.Office.Interop.Excel;使用中