asp.net

C#读取excel数据到datatable中

2022-03-11

public static DataTable ImportExcelToDataTable2(string path)

{

    string conStr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data source={0}; Extended Properties=Excel 12.0;", path);

    using (OleDbConnection conn=new OleDbConnection(conStr))

    {

        conn.Open();

        //获取所有Sheet的相关信息

       DataTable dtSheet = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);

      //获取第一个 Sheet的名称

      string sheetName = dtSheet.Rows[0]["Table_Name"].ToString();

      string sql = string.Format("select * from [{0}]",sheetName);

      using (OleDbDataAdapter oda = new OleDbDataAdapter(sql, conn))

      {

         DataTable dt = new DataTable();

        oda.Fill(dt);

        return dt;

      }

   }

}