Maliq
Maliq

Reputation: 345

Get Values for text box from a Excel cell in C#

I need to get loaded data from excel to textboxes.

I know how to get it viewed in GridView, but I need to get a specific cell value to be captured to a text box.

Example: TextBox FirstName should be captured from Cell A3 LastName should be captured from Cell A4.

Can anybody help to sort it easily?

Edited on 11/6/2013

I have tried below code and it's working but I have put a separate reader to capture each text box value but it will capture only data in first row. Can anyone help to read and capture from row and column difference cell values at once?

string constrg = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Txtpath.Text + ";Extended Properties=Excel 12.0;";
OleDbConnection conns = new OleDbConnection(constrg);


OleDbDataReader dr;
try
{
    conns.Open();
    OleDbCommand cmd = new OleDbCommand("Select * From [Sheet1$A10:H18]", conns);
    dr = cmd.ExecuteReader();
    if (dr.HasRows == false)
    {
        throw new Exception();
    }
    if (dr.Read())
    {
        
        TxtCluster.Text = dr[2].ToString();
        TxtPGroup.Text = dr[6].ToString();
                        
    }

    OleDbCommand cmd1 = new OleDbCommand("Select * From [Sheet1$A11:H18]", conns);
    dr = cmd1.ExecuteReader();
    if (dr.HasRows == false)
    {
        throw new Exception();
    }
    if (dr.Read())
    {
        
        TxtJbsize.Text = dr[2].ToString();
        TxtOsource.Text = dr[6].ToString();

    }

    OleDbCommand cmd2 = new OleDbCommand("Select * From [Sheet1$A12:H18]", conns);
    dr = cmd2.ExecuteReader();
    if (dr.HasRows == false)
    {
        throw new Exception();
    }
    if (dr.Read())
    {

        TxtNoPg.Text = dr[2].ToString();
        TxtProject.Text = dr[6].ToString();

    }

Upvotes: 0

Views: 6636

Answers (2)

Harish
Harish

Reputation: 160

Try this link How to read excel data into datatable using open xml

OpenDocument(strfileLocation, true);
OpenSheet("Sheet1");
ReadDocument(ref dtData);

You will get the data in a datatable, after that you can get your firstname and lastname by appending the column like this

txtFirstName.Text = dtData.rows[0]["C3"].toString();
txtLastName.Text = dtData.rows[0]["C4"].toString();

Upvotes: 2

A9S6
A9S6

Reputation: 6675

You can get data from Excel in following ways:

  1. Use Excel automation to start an instance of Excel programmatically, load the required workbook into it and access cell data.
  2. Use the OLEDB provider for Excel and access worksheets as a table.

Upvotes: 0

Related Questions