How to import data from Excel sheet to data Table in c#?









up vote
2
down vote

favorite
1












I have three four columns in excelsheet such as Firstname, LastName, Email,Phone no also.



I am using Asp.net with C#.



I need to Import data from Excel sheet to DataTable in asp.net with C#.



I have 100000 records in excel sheet. how to use while upload excel sheet?



If any one knows that, please let me know.



Thanks.










share|improve this question























  • correct your question first
    – Suji
    Jul 21 '14 at 4:55










  • Use LinqToExcel
    – Johnny
    Jul 21 '14 at 5:06










  • Thanks Johnny,does it fast to retreive 1 Lacs Records from excelsheet using LinqToExcel? if so How can i improve that?
    – Thinksright
    Jul 21 '14 at 5:09















up vote
2
down vote

favorite
1












I have three four columns in excelsheet such as Firstname, LastName, Email,Phone no also.



I am using Asp.net with C#.



I need to Import data from Excel sheet to DataTable in asp.net with C#.



I have 100000 records in excel sheet. how to use while upload excel sheet?



If any one knows that, please let me know.



Thanks.










share|improve this question























  • correct your question first
    – Suji
    Jul 21 '14 at 4:55










  • Use LinqToExcel
    – Johnny
    Jul 21 '14 at 5:06










  • Thanks Johnny,does it fast to retreive 1 Lacs Records from excelsheet using LinqToExcel? if so How can i improve that?
    – Thinksright
    Jul 21 '14 at 5:09













up vote
2
down vote

favorite
1









up vote
2
down vote

favorite
1






1





I have three four columns in excelsheet such as Firstname, LastName, Email,Phone no also.



I am using Asp.net with C#.



I need to Import data from Excel sheet to DataTable in asp.net with C#.



I have 100000 records in excel sheet. how to use while upload excel sheet?



If any one knows that, please let me know.



Thanks.










share|improve this question















I have three four columns in excelsheet such as Firstname, LastName, Email,Phone no also.



I am using Asp.net with C#.



I need to Import data from Excel sheet to DataTable in asp.net with C#.



I have 100000 records in excel sheet. how to use while upload excel sheet?



If any one knows that, please let me know.



Thanks.







asp.net






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 21 '14 at 12:32









milan m

59921429




59921429










asked Jul 21 '14 at 4:44









Thinksright

11114




11114











  • correct your question first
    – Suji
    Jul 21 '14 at 4:55










  • Use LinqToExcel
    – Johnny
    Jul 21 '14 at 5:06










  • Thanks Johnny,does it fast to retreive 1 Lacs Records from excelsheet using LinqToExcel? if so How can i improve that?
    – Thinksright
    Jul 21 '14 at 5:09

















  • correct your question first
    – Suji
    Jul 21 '14 at 4:55










  • Use LinqToExcel
    – Johnny
    Jul 21 '14 at 5:06










  • Thanks Johnny,does it fast to retreive 1 Lacs Records from excelsheet using LinqToExcel? if so How can i improve that?
    – Thinksright
    Jul 21 '14 at 5:09
















correct your question first
– Suji
Jul 21 '14 at 4:55




correct your question first
– Suji
Jul 21 '14 at 4:55












Use LinqToExcel
– Johnny
Jul 21 '14 at 5:06




Use LinqToExcel
– Johnny
Jul 21 '14 at 5:06












Thanks Johnny,does it fast to retreive 1 Lacs Records from excelsheet using LinqToExcel? if so How can i improve that?
– Thinksright
Jul 21 '14 at 5:09





Thanks Johnny,does it fast to retreive 1 Lacs Records from excelsheet using LinqToExcel? if so How can i improve that?
– Thinksright
Jul 21 '14 at 5:09













2 Answers
2






active

oldest

votes

















up vote
0
down vote













Use the following code:



public static DataTable exceldata(string filePath)

DataTable dtexcel = new DataTable();
bool hasHeaders = false;
string HDR = hasHeaders ? "Yes" : "No";
string strConn;
if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties="Excel 12.0;HDR=" + HDR + ";IMEX=0"";
else
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties="Excel 8.0;HDR=" + HDR + ";IMEX=0"";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object null, null, null, "TABLE" );
//Looping Total Sheet of Xl File
/*foreach (DataRow schemaRow in schemaTable.Rows)

*/
//Looping a first Sheet of Xl File
DataRow schemaRow = schemaTable.Rows[0];
string sheet = schemaRow["TABLE_NAME"].ToString();
if (!sheet.EndsWith("_"))

string query = "SELECT * FROM [" + sheet3 + "]";
OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
dtexcel.Locale = CultureInfo.CurrentCulture;
daexcel.Fill(dtexcel);


conn.Close();
return dtexcel;




Source: http://www.codeproject.com/Questions/445400/Read-Excel-Sheet-Data-into-DataTable



You may also refer the following question: Importing Excel into a DataTable Quickly if you wish to import faster.






share|improve this answer





























    up vote
    0
    down vote













    I'm not sure if this will work in ASP.NET but it works in WPF so maybe there's something you can take from it?



    Anyway, at the global scope:



    Microsoft.Office.Interop.Excel.Application xls;


    Then to select and read a spreadsheet:



     private void readSheet()
    *xls;.xlsx";
    var browsefile = openfile.ShowDialog();

    if (browsefile == true)

    string path = openfile.FileName;

    xls = new Microsoft.Office.Interop.Excel.Application();

    // Dynamic File Using Uploader... Note the readOnly flag is true
    Workbook excelBook = xls.Workbooks.Open(path, 0, true, 5, "", "", true, XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
    Worksheet excelSheet = (Worksheet)excelBook.Worksheets.get_Item(1); ;
    Range excelRange = excelSheet.UsedRange;

    // Make default cell contents
    string strCellData = String.Empty;
    double douCellData;

    // Initialise row and column
    int rowCnt, colCnt = 0;

    // Initialise DataTable
    System.Data.DataTable dt = new System.Data.DataTable();

    // Loop through first row of columns to make header
    for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)

    string strColumn = "";
    strColumn = Convert.ToString((excelRange.Cells[1, colCnt] as Range).Value2);
    var Column = dt.Columns.Add();
    Column.DataType = Type.GetType("System.String");

    // Check & rename for duplicate entries
    if (dt.Columns.Contains(strColumn))
    Column.ColumnName = (strColumn + ", " + colCnt);
    else
    Column.ColumnName = strColumn;

    dt.AcceptChanges();

    // Fill in the rest of the cells
    for (rowCnt = 2; rowCnt <= excelRange.Rows.Count; rowCnt++)

    string strData = "";
    for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)

    try
    ";

    catch (Exception ex)

    douCellData = (excelRange.Cells[rowCnt, colCnt] as Range).Value2;
    strData += douCellData.ToString() + "

    strData = strData.Remove(strData.Length - 1, 1);
    dt.Rows.Add(strData.Split('

    dtGrid.ItemsSource = dt.DefaultView;
    try

    excelBook.Close(true, null, null);

    catch (System.Runtime.InteropServices.COMException comEX)

    Console.Write("COM Exception: " + comEX.ToString());

    xls.Quit();







    share|improve this answer




















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24857876%2fhow-to-import-data-from-excel-sheet-to-data-table-in-c%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      0
      down vote













      Use the following code:



      public static DataTable exceldata(string filePath)

      DataTable dtexcel = new DataTable();
      bool hasHeaders = false;
      string HDR = hasHeaders ? "Yes" : "No";
      string strConn;
      if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
      strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties="Excel 12.0;HDR=" + HDR + ";IMEX=0"";
      else
      strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties="Excel 8.0;HDR=" + HDR + ";IMEX=0"";
      OleDbConnection conn = new OleDbConnection(strConn);
      conn.Open();
      DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object null, null, null, "TABLE" );
      //Looping Total Sheet of Xl File
      /*foreach (DataRow schemaRow in schemaTable.Rows)

      */
      //Looping a first Sheet of Xl File
      DataRow schemaRow = schemaTable.Rows[0];
      string sheet = schemaRow["TABLE_NAME"].ToString();
      if (!sheet.EndsWith("_"))

      string query = "SELECT * FROM [" + sheet3 + "]";
      OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
      dtexcel.Locale = CultureInfo.CurrentCulture;
      daexcel.Fill(dtexcel);


      conn.Close();
      return dtexcel;




      Source: http://www.codeproject.com/Questions/445400/Read-Excel-Sheet-Data-into-DataTable



      You may also refer the following question: Importing Excel into a DataTable Quickly if you wish to import faster.






      share|improve this answer


























        up vote
        0
        down vote













        Use the following code:



        public static DataTable exceldata(string filePath)

        DataTable dtexcel = new DataTable();
        bool hasHeaders = false;
        string HDR = hasHeaders ? "Yes" : "No";
        string strConn;
        if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
        strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties="Excel 12.0;HDR=" + HDR + ";IMEX=0"";
        else
        strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties="Excel 8.0;HDR=" + HDR + ";IMEX=0"";
        OleDbConnection conn = new OleDbConnection(strConn);
        conn.Open();
        DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object null, null, null, "TABLE" );
        //Looping Total Sheet of Xl File
        /*foreach (DataRow schemaRow in schemaTable.Rows)

        */
        //Looping a first Sheet of Xl File
        DataRow schemaRow = schemaTable.Rows[0];
        string sheet = schemaRow["TABLE_NAME"].ToString();
        if (!sheet.EndsWith("_"))

        string query = "SELECT * FROM [" + sheet3 + "]";
        OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
        dtexcel.Locale = CultureInfo.CurrentCulture;
        daexcel.Fill(dtexcel);


        conn.Close();
        return dtexcel;




        Source: http://www.codeproject.com/Questions/445400/Read-Excel-Sheet-Data-into-DataTable



        You may also refer the following question: Importing Excel into a DataTable Quickly if you wish to import faster.






        share|improve this answer
























          up vote
          0
          down vote










          up vote
          0
          down vote









          Use the following code:



          public static DataTable exceldata(string filePath)

          DataTable dtexcel = new DataTable();
          bool hasHeaders = false;
          string HDR = hasHeaders ? "Yes" : "No";
          string strConn;
          if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
          strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties="Excel 12.0;HDR=" + HDR + ";IMEX=0"";
          else
          strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties="Excel 8.0;HDR=" + HDR + ";IMEX=0"";
          OleDbConnection conn = new OleDbConnection(strConn);
          conn.Open();
          DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object null, null, null, "TABLE" );
          //Looping Total Sheet of Xl File
          /*foreach (DataRow schemaRow in schemaTable.Rows)

          */
          //Looping a first Sheet of Xl File
          DataRow schemaRow = schemaTable.Rows[0];
          string sheet = schemaRow["TABLE_NAME"].ToString();
          if (!sheet.EndsWith("_"))

          string query = "SELECT * FROM [" + sheet3 + "]";
          OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
          dtexcel.Locale = CultureInfo.CurrentCulture;
          daexcel.Fill(dtexcel);


          conn.Close();
          return dtexcel;




          Source: http://www.codeproject.com/Questions/445400/Read-Excel-Sheet-Data-into-DataTable



          You may also refer the following question: Importing Excel into a DataTable Quickly if you wish to import faster.






          share|improve this answer














          Use the following code:



          public static DataTable exceldata(string filePath)

          DataTable dtexcel = new DataTable();
          bool hasHeaders = false;
          string HDR = hasHeaders ? "Yes" : "No";
          string strConn;
          if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
          strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties="Excel 12.0;HDR=" + HDR + ";IMEX=0"";
          else
          strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties="Excel 8.0;HDR=" + HDR + ";IMEX=0"";
          OleDbConnection conn = new OleDbConnection(strConn);
          conn.Open();
          DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object null, null, null, "TABLE" );
          //Looping Total Sheet of Xl File
          /*foreach (DataRow schemaRow in schemaTable.Rows)

          */
          //Looping a first Sheet of Xl File
          DataRow schemaRow = schemaTable.Rows[0];
          string sheet = schemaRow["TABLE_NAME"].ToString();
          if (!sheet.EndsWith("_"))

          string query = "SELECT * FROM [" + sheet3 + "]";
          OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
          dtexcel.Locale = CultureInfo.CurrentCulture;
          daexcel.Fill(dtexcel);


          conn.Close();
          return dtexcel;




          Source: http://www.codeproject.com/Questions/445400/Read-Excel-Sheet-Data-into-DataTable



          You may also refer the following question: Importing Excel into a DataTable Quickly if you wish to import faster.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 23 '17 at 12:32









          Community

          11




          11










          answered Jul 21 '14 at 5:15









          milan m

          59921429




          59921429






















              up vote
              0
              down vote













              I'm not sure if this will work in ASP.NET but it works in WPF so maybe there's something you can take from it?



              Anyway, at the global scope:



              Microsoft.Office.Interop.Excel.Application xls;


              Then to select and read a spreadsheet:



               private void readSheet()
              *xls;.xlsx";
              var browsefile = openfile.ShowDialog();

              if (browsefile == true)

              string path = openfile.FileName;

              xls = new Microsoft.Office.Interop.Excel.Application();

              // Dynamic File Using Uploader... Note the readOnly flag is true
              Workbook excelBook = xls.Workbooks.Open(path, 0, true, 5, "", "", true, XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
              Worksheet excelSheet = (Worksheet)excelBook.Worksheets.get_Item(1); ;
              Range excelRange = excelSheet.UsedRange;

              // Make default cell contents
              string strCellData = String.Empty;
              double douCellData;

              // Initialise row and column
              int rowCnt, colCnt = 0;

              // Initialise DataTable
              System.Data.DataTable dt = new System.Data.DataTable();

              // Loop through first row of columns to make header
              for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)

              string strColumn = "";
              strColumn = Convert.ToString((excelRange.Cells[1, colCnt] as Range).Value2);
              var Column = dt.Columns.Add();
              Column.DataType = Type.GetType("System.String");

              // Check & rename for duplicate entries
              if (dt.Columns.Contains(strColumn))
              Column.ColumnName = (strColumn + ", " + colCnt);
              else
              Column.ColumnName = strColumn;

              dt.AcceptChanges();

              // Fill in the rest of the cells
              for (rowCnt = 2; rowCnt <= excelRange.Rows.Count; rowCnt++)

              string strData = "";
              for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)

              try
              ";

              catch (Exception ex)

              douCellData = (excelRange.Cells[rowCnt, colCnt] as Range).Value2;
              strData += douCellData.ToString() + "

              strData = strData.Remove(strData.Length - 1, 1);
              dt.Rows.Add(strData.Split('

              dtGrid.ItemsSource = dt.DefaultView;
              try

              excelBook.Close(true, null, null);

              catch (System.Runtime.InteropServices.COMException comEX)

              Console.Write("COM Exception: " + comEX.ToString());

              xls.Quit();







              share|improve this answer
























                up vote
                0
                down vote













                I'm not sure if this will work in ASP.NET but it works in WPF so maybe there's something you can take from it?



                Anyway, at the global scope:



                Microsoft.Office.Interop.Excel.Application xls;


                Then to select and read a spreadsheet:



                 private void readSheet()
                *xls;.xlsx";
                var browsefile = openfile.ShowDialog();

                if (browsefile == true)

                string path = openfile.FileName;

                xls = new Microsoft.Office.Interop.Excel.Application();

                // Dynamic File Using Uploader... Note the readOnly flag is true
                Workbook excelBook = xls.Workbooks.Open(path, 0, true, 5, "", "", true, XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
                Worksheet excelSheet = (Worksheet)excelBook.Worksheets.get_Item(1); ;
                Range excelRange = excelSheet.UsedRange;

                // Make default cell contents
                string strCellData = String.Empty;
                double douCellData;

                // Initialise row and column
                int rowCnt, colCnt = 0;

                // Initialise DataTable
                System.Data.DataTable dt = new System.Data.DataTable();

                // Loop through first row of columns to make header
                for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)

                string strColumn = "";
                strColumn = Convert.ToString((excelRange.Cells[1, colCnt] as Range).Value2);
                var Column = dt.Columns.Add();
                Column.DataType = Type.GetType("System.String");

                // Check & rename for duplicate entries
                if (dt.Columns.Contains(strColumn))
                Column.ColumnName = (strColumn + ", " + colCnt);
                else
                Column.ColumnName = strColumn;

                dt.AcceptChanges();

                // Fill in the rest of the cells
                for (rowCnt = 2; rowCnt <= excelRange.Rows.Count; rowCnt++)

                string strData = "";
                for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)

                try
                ";

                catch (Exception ex)

                douCellData = (excelRange.Cells[rowCnt, colCnt] as Range).Value2;
                strData += douCellData.ToString() + "

                strData = strData.Remove(strData.Length - 1, 1);
                dt.Rows.Add(strData.Split('

                dtGrid.ItemsSource = dt.DefaultView;
                try

                excelBook.Close(true, null, null);

                catch (System.Runtime.InteropServices.COMException comEX)

                Console.Write("COM Exception: " + comEX.ToString());

                xls.Quit();







                share|improve this answer






















                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  I'm not sure if this will work in ASP.NET but it works in WPF so maybe there's something you can take from it?



                  Anyway, at the global scope:



                  Microsoft.Office.Interop.Excel.Application xls;


                  Then to select and read a spreadsheet:



                   private void readSheet()
                  *xls;.xlsx";
                  var browsefile = openfile.ShowDialog();

                  if (browsefile == true)

                  string path = openfile.FileName;

                  xls = new Microsoft.Office.Interop.Excel.Application();

                  // Dynamic File Using Uploader... Note the readOnly flag is true
                  Workbook excelBook = xls.Workbooks.Open(path, 0, true, 5, "", "", true, XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
                  Worksheet excelSheet = (Worksheet)excelBook.Worksheets.get_Item(1); ;
                  Range excelRange = excelSheet.UsedRange;

                  // Make default cell contents
                  string strCellData = String.Empty;
                  double douCellData;

                  // Initialise row and column
                  int rowCnt, colCnt = 0;

                  // Initialise DataTable
                  System.Data.DataTable dt = new System.Data.DataTable();

                  // Loop through first row of columns to make header
                  for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)

                  string strColumn = "";
                  strColumn = Convert.ToString((excelRange.Cells[1, colCnt] as Range).Value2);
                  var Column = dt.Columns.Add();
                  Column.DataType = Type.GetType("System.String");

                  // Check & rename for duplicate entries
                  if (dt.Columns.Contains(strColumn))
                  Column.ColumnName = (strColumn + ", " + colCnt);
                  else
                  Column.ColumnName = strColumn;

                  dt.AcceptChanges();

                  // Fill in the rest of the cells
                  for (rowCnt = 2; rowCnt <= excelRange.Rows.Count; rowCnt++)

                  string strData = "";
                  for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)

                  try
                  ";

                  catch (Exception ex)

                  douCellData = (excelRange.Cells[rowCnt, colCnt] as Range).Value2;
                  strData += douCellData.ToString() + "

                  strData = strData.Remove(strData.Length - 1, 1);
                  dt.Rows.Add(strData.Split('

                  dtGrid.ItemsSource = dt.DefaultView;
                  try

                  excelBook.Close(true, null, null);

                  catch (System.Runtime.InteropServices.COMException comEX)

                  Console.Write("COM Exception: " + comEX.ToString());

                  xls.Quit();







                  share|improve this answer












                  I'm not sure if this will work in ASP.NET but it works in WPF so maybe there's something you can take from it?



                  Anyway, at the global scope:



                  Microsoft.Office.Interop.Excel.Application xls;


                  Then to select and read a spreadsheet:



                   private void readSheet()
                  *xls;.xlsx";
                  var browsefile = openfile.ShowDialog();

                  if (browsefile == true)

                  string path = openfile.FileName;

                  xls = new Microsoft.Office.Interop.Excel.Application();

                  // Dynamic File Using Uploader... Note the readOnly flag is true
                  Workbook excelBook = xls.Workbooks.Open(path, 0, true, 5, "", "", true, XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
                  Worksheet excelSheet = (Worksheet)excelBook.Worksheets.get_Item(1); ;
                  Range excelRange = excelSheet.UsedRange;

                  // Make default cell contents
                  string strCellData = String.Empty;
                  double douCellData;

                  // Initialise row and column
                  int rowCnt, colCnt = 0;

                  // Initialise DataTable
                  System.Data.DataTable dt = new System.Data.DataTable();

                  // Loop through first row of columns to make header
                  for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)

                  string strColumn = "";
                  strColumn = Convert.ToString((excelRange.Cells[1, colCnt] as Range).Value2);
                  var Column = dt.Columns.Add();
                  Column.DataType = Type.GetType("System.String");

                  // Check & rename for duplicate entries
                  if (dt.Columns.Contains(strColumn))
                  Column.ColumnName = (strColumn + ", " + colCnt);
                  else
                  Column.ColumnName = strColumn;

                  dt.AcceptChanges();

                  // Fill in the rest of the cells
                  for (rowCnt = 2; rowCnt <= excelRange.Rows.Count; rowCnt++)

                  string strData = "";
                  for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)

                  try
                  ";

                  catch (Exception ex)

                  douCellData = (excelRange.Cells[rowCnt, colCnt] as Range).Value2;
                  strData += douCellData.ToString() + "

                  strData = strData.Remove(strData.Length - 1, 1);
                  dt.Rows.Add(strData.Split('

                  dtGrid.ItemsSource = dt.DefaultView;
                  try

                  excelBook.Close(true, null, null);

                  catch (System.Runtime.InteropServices.COMException comEX)

                  Console.Write("COM Exception: " + comEX.ToString());

                  xls.Quit();








                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jul 1 '16 at 8:23









                  Jonas Bezzubovas

                  15219




                  15219



























                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24857876%2fhow-to-import-data-from-excel-sheet-to-data-table-in-c%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      這個網誌中的熱門文章

                      How to read a connectionString WITH PROVIDER in .NET Core?

                      Museum of Modern and Contemporary Art of Trento and Rovereto

                      In R, how to develop a multiplot heatmap.2 figure showing key labels successfully