0

I need to programmatically open an Excel file that is stored in a MOSS 2007 Shared Documents List. I’d like to use an OleDbConnection so that I may return the contents of the file as a DataTable. I believe this is possile since a number of articles on the Web imply this is possible. Currently my code fails when trying to initialize a new connection (oledbConn = new OleDbConnection(_connStringName); The error message is:

Format of the initialization string does not conform to specification starting at index 0.

I believe I am just not able to figure the right path to the file. Here is my code:

        public DataTable GetData(string fileName, string workSheetName, string filePath)
    {   
// filePath == C:\inetpub\wwwroot\wss\VirtualDirectories\80\MySpWebAppName\Shared Documents\FY12_FHP_SPREADSHEET.xlsx
            // Initialize global vars
        _connStringName = DataSource.Conn_Excel(fileName, filePath).ToString();
        _workSheetName = workSheetName;
        dt = new DataTable();
        //Create the connection object
        if (!string.IsNullOrEmpty(_connStringName))
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                oledbConn = new OleDbConnection(_connStringName);

                try
                {

                    oledbConn.Open();
                    //Create OleDbCommand obj and select data from worksheet GrandTotals
                    OleDbCommand cmd = new OleDbCommand("SELECT * FROM " + _workSheetName + ";", oledbConn);

                    //create new OleDbDataAdapter
                    OleDbDataAdapter oleda = new OleDbDataAdapter();
                    oleda.SelectCommand = cmd;
                    oleda.Fill(dt);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
                finally
                {
                    oledbConn.Close();
                }
            });
        }
        return dt;
    }

        public static OleDbConnection Conn_Excel(string ExcelFileName, string filePath)
    {
// filePath == C:\inetpub\wwwroot\wss\VirtualDirectories\80\MySpWebAppName\Shared Documents\FY12_FHP_SPREADSHEET.xlsx
OleDbConnection myConn = new OleDbConnection();
        myConn.ConnectionString = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0");
        return myConn;
    }

What am I doing wrong, or is there a better way to get the Excel file contents as a DataTable?

Community
  • 1
  • 1
Bengal
  • 329
  • 4
  • 21

1 Answers1

0

I ended up using the open source project Excel Data Reader

Bengal
  • 329
  • 4
  • 21