Thursday, August 14, 2014

Refresh the excel file using SSIS

C# code to refresh the excel report using SSIS Script task:

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
            ExcelRefresh(@"E:\TEST.xls");
            Dts.TaskResult = (int)ScriptResults.Success;
        }
     
        private void ExcelRefresh(string Filename)
        {
            object NullValue = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            excelApp.DisplayAlerts = false;
            Microsoft.Office.Interop.Excel.Workbook Workbook = excelApp.Workbooks.Open(
               Filename, NullValue, NullValue, NullValue, NullValue,
               NullValue, NullValue, NullValue, NullValue, NullValue,
               NullValue, NullValue, NullValue, NullValue, NullValue);
            Workbook.RefreshAll();
            System.Threading.Thread.Sleep(20000);
                     
            Workbook.Save();
            Workbook.Close(false, Filename, null);
            excelApp.Quit();
            Workbook = null;
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
        }
-------------
Incase if you get any error like 'Cannot be embbedded. Use the applicable interface instead [duplicate]' then 
follow the below step:

Go to References - find the Microsoft Office Interop reference - Right click - select properties 
- change 'Embed Intero Types' to false.

No comments:

Post a Comment

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