Excel Automation ... Accomodate Excel 2003 and 2007 Workbooks

Posted on 2009-05-04
Last Modified: 2013-12-17
Hi -

I have a application that works with Excel 2003 but now users are using Excel 2007.  We want to make the app work with 2003 and 2007.

Background:  I developed an application that automates Excel 2003 using C#.Net in VS 2005.  The development machine has Excel 2003 loaded on it.  The C#.Net application set references the the Office and Excel 11.0 object library.  The User machine also had Excel 2003 loaded on it.  The application "builded", deployed, installed and ran just fine on the user's machine.

Change:  The users are now saving Excel workbooks in both Excel 2003 and Excel 2007 and of course we want the C#.Net program to be able to read both formats (i.e., the Excel 2003 format (.xls) and the three Excel 2007 formats ... .xlsx, .xlsm and .xlsb).

Question:  What do I have to do to the original program to make it work with Excel 2003 and 2007?

It seems to me that I have to load Excel 2007 on the development machine and revise the reference to the Office/Excel 2007 Object Library 12.0 ... do I then drop the reference to the Office/Excel 2003 11.0?

Also need to adjust the connection string.  If Excel 2003 then the Provider is Jet; If Excel 2007 then Provider is Ace.  Something like this:

if (extension == ".xls")
  conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + file + ";" +      "Extended Properties=Excel 8.0;");
   conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + file + ";" + "Extended Properties

I've also included the (abbreviated) original Code in case there is something else I need to do:

using System;

using System.Collections.Generic;

using System.Text;

using System.Collections;

using System.Data;

using System.Data.OleDb;

using Excel = Microsoft.Office.Interop.Excel;

using System.Reflection;

using System.Windows.Forms;

using System.Data.SqlClient;

using System.Diagnostics;

namespace BusinessTier


    public class GetExcelData


        //Holds Map of Excel Field Names to Database Field Names

        //private Hashtable ht = new Hashtable();

        public GetExcelData()




        public DataTable GetExcelDataTable(string filepath, string filename, string sheetname)


            string cnstr = BuildConnectionString(filepath, filename);

            DataTable dt = GetExcelDataTable(cnstr, sheetname, filepath, filename);

            return dt;


        private string BuildConnectionString(string filepath, string filename)


            //The "IMEX=1" parameter was added to force fields with mixed coding (both numeric and text) to import to C# as a text field.

            //  This bypasses Excel's nature of picking a data type based on the majority datatypes in the column of cell (e.g., if more cells 

            //  in the column contained text than numeric, Excel/C# assigns a string datatype to the field, nullifying numeric values)

            return ("Provider=Microsoft.Jet.OLEDB.4.0;" +

                    "Data Source=" +

                    filepath + filename + ";" +

                    @"Extended Properties=""Excel 8.0;IMEX=1;""");

                    //"Extended Properties=Excel 8.0;");


        private DataTable GetExcelDataTable(string cnstr, string sheetname, string pathname, string filename)


            string cn = cnstr;

            DataTable dtTreatyType = new DataTable();

            string select = String.Empty;

            DataTable dt = new DataTable();



                OleDbDataAdapter daTreatyType = new OleDbDataAdapter("SELECT * FROM [Data Capture$E1:E2] ", cn);


                if (dtTreatyType.Rows[0][0].ToString() == "CAT")

                    select = "SELECT * FROM [Data Capture$A1:HJ7] ";


                    select = "SELECT * FROM [Data Capture$A1:HJ17] ";

                OleDbDataAdapter da = new OleDbDataAdapter(select , cn);



            catch (Exception e)


               throw new Exception(e.Message); 


            //If excel decides that the column of "Reinsurance Rate Changes" is

            //  of type string then we did not get the change information.

            //  Open the Excel sheet and get the data cell by cell.


            if (dt.Columns[64].DataType == Type.GetType("System.String"))




                    GetReinsuranceRateChange(pathname, filename, dt);


                catch (Exception ex)


                    throw new Exception(ex.Message);




            //This little loop dumps column infomation to the Debug window

            //  Comment out for now

            //foreach (DataColumn c in dt.Columns)

            //    Debug.WriteLine (c.ColumnName + ":  " + c.DataType.ToString());

            return dt;


        private void GetReinsuranceRateChange(string pathname, string filename, DataTable dt)


            //Declare excel variables

            Excel.Application xlApp = null;

            Excel.Workbook xlBook = null;

            Excel.Sheets xlSheets = null;

            Excel.Worksheet xlWkSheet = null;

            //Excel.Range xlEPIRange = null;

            Excel.Range xlRange = null;



                object oMissing = Missing.Value;

                //Instantiate the Excel and open the file

                xlApp = new Excel.Application();

                xlBook = xlApp.Workbooks.Open(pathname + filename,

                    false, true, oMissing, oMissing, oMissing, oMissing,

                    oMissing, oMissing, oMissing, oMissing, oMissing,

                    oMissing, oMissing, oMissing);

                xlSheets = xlBook.Worksheets;

                xlWkSheet = (Excel.Worksheet)xlSheets.get_Item("Data Capture");

                int rowCount = 0;

                foreach (DataRow row in dt.Rows)



                    xlRange = (Excel.Range)xlWkSheet.get_Range("BM" + (rowCount + 1).ToString() + ":BM" + (rowCount + 1).ToString(), Type.Missing);

                    if (IsNumeric(xlRange.Cells.Value2.ToString()))

                        row[64] = xlRange.Cells.Value2.ToString();


                        row[64] = null;


                xlBook.Close(false, oMissing, oMissing);


                xlBook = null;



                xlApp = null;


            catch (Exception e)


                //Throw exception if there is trouble

                throw new Exception(e.Message);




        private static bool IsNumeric(string p)





                return true;




               return false;





Open in new window

Question by:MarkMahon
  • 2
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
Could you use a 3rd party components that could read both 2003/2007 spreadsheets:

Author Comment

Comment Utility
emoreau -

Thanks for the suggestion.  But I'd like to try to solve this before turning to a 3rd party vendor.


Accepted Solution

MarkMahon earned 0 total points
Comment Utility
I got it to work using the changes indicated in the original question.

The thing that is different between Excel 2003 and Excel 2007 was the interpretation of what a cell in the excel worksheet with the formula  ="" means.  In Excel 2003 ="" is interpreted as a null value, whereas Excel 2007 interprets it as a text value ... which of course stinks.  It forces me to read the cells in the worksheet cell by cell.

Hopes this helps the next person.


Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This article descibes how to create a connection between Excel and SAP and how to move data from Excel to SAP or the other way around.
The view will learn how to download and install SIMTOOLS and FORMLIST into Excel, how to use SIMTOOLS to generate a Monte Carlo simulation of 30 sales calls, and how to calculate the conditional probability based on the results of the Monte Carlo …
The viewer will learn how to use the =DISCRINV command to create a discrete random variable, use this command to model a set of probabilities and outcomes in a Monte Carlo simulation, and learn how to find the standard deviation of a set of probabil…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now