Tuesday, August 19, 2014

How to automatically refresh PivotTable in excel

Below is the C# code to refresh the pivottable in excel workbook


using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
--------------------


public void Main()

{
// TODO: Add your code here
            string path = Dts.Variables["$Project::RefreshExcel_Path"].Value.ToString();
            string filename = Dts.Variables["$Project::RefreshExcel_FileName"].Value.ToString();

            PivotRefresh(path + filename);

            Dts.TaskResult = (int)ScriptResults.Success;
}
        
        private void PivotRefresh(string Filename)
        {
            Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();

            //oXL.Visible = true;

            oXL.DisplayAlerts = false;
            Microsoft.Office.Interop.Excel.Workbook mWorkBook = oXL.Workbooks.Open(Filename, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            //Get all the sheets in the workbook
            Microsoft.Office.Interop.Excel.Sheets mWorkSheets = mWorkBook.Worksheets;
            foreach (Microsoft.Office.Interop.Excel.Worksheet pivotSheet in mWorkSheets)
            {
                //Microsoft.Office.Interop.Excel.PivotTables pivotTables = pivotSheet.PivotTables();
                Microsoft.Office.Interop.Excel.PivotTables pivotTables = (Microsoft.Office.Interop.Excel.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
                    }
                }
            }
            mWorkBook.Save();
            mWorkBook.Close(false, Filename, null);
            oXL.Quit();
            mWorkBook = null;
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
        }

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.