Friday, September 16, 2011

How to check database connection in Excel file

Micorsoft Excel supports external data sources such as SQL Server. In terms of database connection, Excel allows both OLEDB connnection and ODBC connection. The following code snippet shows a way of how to detect the DB connection programmatically. The code opens Excel file in the background and check any connection is related to DB connection.

using System;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

namespace FindConnectionInDB
{
   class Program
   {
      static void Main(string[] args)
      {
         string xlsfile = @"c:\temp\book1.xlsx";

         Program p = new Program();
         bool ret = p.CheckDbConnectionInExcel(xlsfile);
         Console.WriteLine("Has DB Connection : {0}", ret);
      }

      public bool CheckDbConnectionInExcel(string excelFile)
      {
         bool hasDBConnection = false;
         Excel.Application excelApp = null;
         Excel.Workbook wb = null;

         try
         {
            excelApp = new Excel.Application();
            wb = excelApp.Workbooks.Open(excelFile);

            for (int i = 1; i <= wb.Connections.Count; i++)
            {
               if (wb.Connections[i].Type == Excel.XlConnectionType.xlConnectionTypeOLEDB ||
                   wb.Connections[i].Type == Excel.XlConnectionType.xlConnectionTypeODBC)
               {
                  hasDBConnection = true;
                  break;
               }
            }

            wb.Close(true);
            excelApp.Quit();
         }
         finally
         {                        
            ReleaseExcelObject(wb);
            ReleaseExcelObject(excelApp);
         }

         return hasDBConnection;
      }

      private void ReleaseExcelObject(object obj)
      {
         try
         {
            if (obj != null)
            {
               Marshal.ReleaseComObject(obj);
               obj = null;
            }
         }
         catch (Exception ex)
         {
            obj = null;
            throw ex;
         }
         finally
         {
            GC.Collect();
         }
      }
   }
}

One thing to note is that you need to release Excel object by using Marshal.ReleaseComObject() so that in any case your Excel process can be disposed.

No comments:

Post a Comment