Click here to Skip to main content
15,899,679 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I use the following code to read data from an excel file in my c# program, the problem is that it gives an error at the underlined line if the file im supposed to read is not explicitly opened:

<br />
//Getting Sheet Name<br />
            Excel.ApplicationClass app = new ApplicationClass();<br />
            Excel.Workbook workBook = app.Workbooks.Open(textFileName.Text, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, false, false);<br />
            Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;<br />
            app.Visible = false;<br />
            //-----------------------<br />
            if (toolStripProgressBar1.Value == toolStripProgressBar1.Maximum)<br />
            {<br />
                toolStripProgressBar1.Value = toolStripProgressBar1.Minimum;<br />
            }<br />
            toolStripProgressBar1.PerformStep();<br />
            string FileName = workSheet.Name;<br />
            app.Workbooks.Close();<br />
            <br />
            string connectionString = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + textFileName.Text + ";";<br />
            connectionString += "Extended Properties=\"Excel 8.0;HDR=YES;\"";<br />
            //<br />
            OleDbCommand myCommand = new OleDbCommand("Select * from [" + FileName + "$];");<br />
            OleDbConnection myConnection = new OleDbConnection(connectionString);<br />
            myConnection.Open();<br />
            myCommand.Connection = myConnection;<br />
            OleDbDataReader myReader = myCommand.ExecuteReader();<br />
            MessageBox.Show("hello");<br />
            while(myReader.Read())<br />
            {<br />
                if (toolStripProgressBar1.Value == toolStripProgressBar1.Maximum)<br />
                {<br />
                    toolStripProgressBar1.Value = toolStripProgressBar1.Minimum;<br />
                }<br />
                toolStripProgressBar1.PerformStep();<br />
<br />
                TT_DT = myReader.GetDateTime(0);<br />
                Subject = myReader.GetString(1);<br />
                TT_ID = myReader.GetValue(2).ToString();<br />
<br />
                LoadID(TT_DT, Subject, TT_ID);<br />
            }<br />
            myConnection.Close();<br />
Posted

1 solution

Do you mean it only works if Excel has the file open already ? That may be a limitation of reading Excel files that way, if so, I doubt you can fix it without changing your method of reading them.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900