Click here to Skip to main content
15,881,797 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Any working code which will read data from excel using c#
Posted
Comments
Mario Z 19-Aug-15 10:28am    
What have you tried so far? As @CPallini mentioned you can easily search this up and find quite a few solutions based on OLEDB, OpenOffice SDK, etc.

 
Share this answer
 
Comments
[no name] 19-Aug-15 5:37am    
I am not getting proper code
Hi,
Try this code.

C#
private DataTable ExcelToDataTable()
    {
        string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Temp\\Sample.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES'";
        
        OleDbConnection connExcel = new OleDbConnection(conStr);
        connExcel.Open();
        try
        {

            OleDbCommand cmdExcel = new OleDbCommand();
            OleDbDataAdapter oda = new OleDbDataAdapter();
            DataTable dt = new DataTable();
            cmdExcel.Connection = connExcel;

            /*Get the name of First Sheet*/

            DataTable dtexcelSchema;
            dtexcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string sheetName = dtexcelSchema.Rows[0]["TABLE_NAME"].ToString();
            connExcel.Close();

            /*Read Data from First Sheet*/
            connExcel.Open();
            cmdExcel.CommandText = "SELECT * FROM [" + sheetName + "]";
            oda.SelectCommand = cmdExcel;
            oda.Fill(dt);
            connExcel.Close();

            return dt;
        }
        catch (Exception ex)
        {
            connExcel.Close();
            throw ex;
        }
    }
 
Share this answer
 
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ReadFromExcel();
}


private void ReadFromExcel()
{
string con =
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\2015.xlsx;; Extended Properties=Excel 12.0;";
using (OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
OleDbDataReader dr = command.ExecuteReader();
DataTable tab = new DataTable();
tab.Load(dr);
}

}
}
 
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