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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
LVL 70

Expert Comment

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

Author Comment

ID: 24303569
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
ID: 24420774
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to get Spreadsheet Compare 2016 working with the 64 bit version of Office 2016
If you need to forecast numbers -- typically for finance -- the Windows and Mac versions of Excel 2016 have a basket of tools to get the job done.
This Micro Tutorial will demonstrate in Microsoft Excel how to add style and sexy appeal to horizontal bar charts.
This Micro Tutorial will demonstrate the scrolling table in Microsoft Excel using the INDEX function.

621 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