C converts the data in Excel to DataSet

  • 2021-01-03 21:01:28
  • OfStack

Use C# to convert data in Excel to DataSet without the aid of a third party plug-in


/// <summary>
    /// EXCEL Data conversion DataSet
    /// </summary>
    /// <param name="filePath"> Full file path </param>
    /// <param name="search"> The name of the table </param>
    /// <returns></returns>    
    private DataSet GetDataSet(string fileName)
    {
      string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';";
      OleDbConnection objConn = null;
      objConn = new OleDbConnection(strConn);
      objConn.Open();
      DataSet ds = new DataSet();
      //List<string> List = new List<string> { " Payment amount ", " Paid the tariff ", " advancements ", " Beyond the ", " To account the profits " };
      List<string> List = new List<string> { };
      DataTable dtSheetName = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
      foreach (DataRow dr in dtSheetName.Rows)
      {
        if (dr["Table_Name"].ToString().Contains("$") && !dr[2].ToString().EndsWith("$"))
        {
          continue;
        }
        string s = dr["Table_Name"].ToString();
        List.Add(s);
      }
      try
      {
        for (int i = 0; i < List.Count; i++)
        {
          ds.Tables.Add(List[i]);
          string SheetName = List[i];
          string strSql = "select * from [" + SheetName + "]";
          OleDbDataAdapter odbcCSVDataAdapter = new OleDbDataAdapter(strSql, objConn);
          DataTable dt = ds.Tables[i];
          odbcCSVDataAdapter.Fill(dt);
        }
        return ds;
      }
      catch (Exception ex)
      {
        return null;
      }
      finally
      {
        objConn.Close();
        objConn.Dispose();
      }
    }

This is the end of this article, I hope you enjoy it.


Related articles: