How to import data from excel to datatable in c#

Total Post:412

Points:2888
C# 
C#
 36044  View(s)
Ratings:
Rate this:

Hello Everyone,

I have been facing a problem since last night, actually i want to import data from excel to datatable in C#.Net. So please resolve my problem as soon as possible.

Thanks in advance!!

  1. Post:68

    Points:476
    Re: How to import data from excel to datatable in c#

    Hello Pravesh Singh,

    Check this code...

    System.Data.DataTable
    dtExcel = new System.Data.DataTable();
    dtExcel.TableName = "MyExcelData";
    string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='MyExcelFilePath';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
    OleDbConnection con = new OleDbConnection(SourceConstr);
    string query = "Select * from [Sheet1$]";
    OleDbDataAdapter data = new OleDbDataAdapter(query, con);
    data.Fill(dtExcel);

    It might be resolve your problem.

      Modified On Apr-06-2018 01:09:48 AM
  1. Post:1

    Points:7
    Re: How to import data from excel to datatable in c#

    Hello,
    I want to import data from an Excel file into a database SQL Server 2008, the Excel file contains multiple sheets, each sheet represents a table row e in the database, and I must also respect the constraints intergrités, if you can offer me a code that does almost the same thing THANKS

  1. Post:1

    Points:7
    Re: How to import data from excel to datatable in c#

    Dear arun,
                 thnx for sharing your code, it saved my lots of time.i was getting error when application was deployed on server.
    htnx

  1. Post:1

    Points:7
    Re: How to import data from excel to datatable in c#

    Thank you very much for your solution. For future reference, I've modified your code to ensure object disposal:


    System.Data.DataTable dtExcel = new System.Data.DataTable();
    dtExcel.TableName = "MyExcelData";
    string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='MyExcelFilePath';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
    using (OleDbConnection con = new OleDbConnection(SourceConstr))
    using (OleDbDataAdapter data = new OleDbDataAdapter("Select * from [Sheet1$]", con))
    {
    data.Fill(dtExcel);
    }

      Modified On Apr-06-2018 01:10:13 AM
  1. Post:1

    Points:7
    Re: How to import data from excel to datatable in c#

                    MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\yourfile.xls';Extended Properties=Excel 8.0;");
                    MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
                    MyCommand.TableMappings.Add("Table", "TestTable");
                    DtSet = new System.Data.DataSet();
                    MyCommand.Fill(DtSet);


    Lethal

     

     

     

      Modified On Oct-20-2014 01:43:08 AM

Answer