Click here to Skip to main content
14,970,345 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi!
i am trying to read excel sheet cell in my asp.net here is the code.

C#
string file = Server.MapPath("Model.xls");
            string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties=Excel 8.0;";
            OleDbConnection objConn = new OleDbConnection(connStr);
            objConn.Open();
 DataSet ds;
            OleDbDataAdapter MyCommand;
            
            MyCommand = new OleDbDataAdapter("select * from [Sheet1$B6:B6]", objConn);
            ds = new System.Data.DataSet();
            MyCommand.Fill(ds);
            Label1.Text = (MyCommand.Fill(ds)).ToString();


but it does not show value from that cell. can somebody please tell me what wrong...
Thanks in advance
Posted

1 solution

A dataset is like a in-memory database. This can contain one or more tables. To get the retrieved value from your excel file, you should go inside its table and access the cell there.

Since your select query there returns only one cell from the excel file, you can probably access the value from the dataset this way.
C#
Label1.Text = ds.Tables[0].Rows[0][0].ToString(); //On the [0][0] part, the first index refers to the row index while the second refers to the column index


UPDATE:

It seems that it's treating the value as a header column. I tried your code and made some modifications on the connection string, just added HDR=NO. You may try the code below on your end.

C#
string connStr = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=NO;""", file);
   
v2
Comments
saifullahiit 6-Jan-14 0:17am
   
it gives me the following error.
System.IndexOutOfRangeException: There is no row at position 1. at System.Data.RBTree`1.GetNodeByIndex(Int32 userIndex) at System.Data.DataRowCollection.get_Item(Int32 index) at Default2.Page_Load(Object sender, EventArgs e)
the data on the excel sheet resides in B6 i have tried to put 6 and 2 but i still gave error.
walterhevedeich 6-Jan-14 0:58am
   
I updated my answer. You can try changing your current connection string into what I put there.
saifullahiit 6-Jan-14 1:05am
   
Thank you so much. you were right but a bit changes that i made and i worked fine;
MyCommand = new OleDbDataAdapter("select * from [Sheet1$B6:B6]", objConn);
ds = new System.Data.DataSet();
MyCommand.Fill(ds);
Label1.Text = ds.Tables[0].Rows[0][0].ToString();
//dont change Row[0][0], only change in [Sheet1$B6:B6] to A1 etc
walterhevedeich 6-Jan-14 1:35am
   
So instead of [Sheet1$B6:B6], you changed it to [Sheet1$A1]? Anyway, glad that your solution worked out for you.

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