如何在 C# 中获取 excel table 数据到 LIST

How to get excel table data in to a LIST in c#

我想获取 excel table 值到 c#

中的列表

这是我的代码

           [HttpPost]
    public ActionResult GetExcelData()
    {
        List<ExcelData> exData = new List<ExcelData>();

         string status;
        string fileparth;
        string json;
        using (var reader = new StreamReader(Request.InputStream))
        {
            json = reader.ReadToEnd();
        }
        JObject jo = (JObject)JsonConvert.DeserializeObject(json);
        fileparth = jo.Value<string>("uplaodFile");
        string conString = string.Empty;

        string extension = Path.GetExtension(fileparth);

        switch (extension)
        {
            case ".xls": //Excel 97-03
                conString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'", fileparth);

                break;
            case ".xlsx": //Excel 07 or higher
                conString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES'", fileparth);

                break;

        }
      //  conString = string.Format(conString/*strConnection*/, fileparth/*FileUpload1*/);
        using (OleDbConnection excel_con = new OleDbConnection(conString))
        {
            excel_con.Open();
            string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
            DataTable dtExcelData = new DataTable();

            //[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.

            dtExcelData.Columns.AddRange(new DataColumn[3] { 
                new DataColumn("TRID", typeof(decimal)),
                 new DataColumn("Actual(km)", typeof(string)),
                  new DataColumn("Amount(Rs)", typeof(decimal))
            });
            using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
            {
                oda.Fill(dtExcelData);
            }
            excel_con.Close();
        }
    }

在 excel_con.Close() 之后;

我需要经历一个循环,直到记录在 sheet 中结束。 然后我需要将这些值添加到

exData

这些是 getter 和 setter

                 public class ExcelData
    {
        private decimal _RnEID;

        public decimal RnEID
        {
            get { return _RnEID; }
            set { _RnEID = value; }
        }
        private string _EActual;

        public string EActual
        {
            get { return _EActual; }
            set { _EActual = value; }
        }
        private string _EAmount;

        public string EAmount
        {
            get { return _EAmount; }
            set { _EAmount = value; }
        }
    }

这里是假人excelsheet

请帮我解决这个问题

谢谢大家

如果您想 return List<ExcelData>,则无需加载 DataTable。

实际上,DataAdapter.Fill 方法使用内部 OleDbDataReader 遍历 returned 数据并填充 DataTable。现在,如果您想要 return 一个 List<ExcelData>,您需要在 table 上再次循环并为 table 中的每一行构建一个 ExcelData 类型的元素。

因此,您可以自己完成,而无需适配器填充方法所需的循环。

    List<ExcelData> exData = new List<ExcelData>();
    .....

    using (OleDbConnection excel_con = new OleDbConnection(conString))
    using (OleDbCommand cmd = new OleDBCommand())
    {
        excel_con.Open();
        string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();

        cmd.CommandText = "SELECT * FROM [" + sheet1 + "]";
        cmd.Connection = excel_con;
        using (OleDbDataReader reader = cmd.ExecuteReader())
        {
             ExcelData curLine = new ExcelData();
             curLine.RnEID = (reader.IsDbNull(0) ? 0m : Convert.ToDecimal(reader[0]));
             curLine.EActual = (reader.IsDbNull(1) ? "" : reader[1].ToString());
             curLine.EAmount = (reader.IsDbNull(2) ? 0m : Convert.ToDecimal(reader[2]));
             exData.Add(curLine);
        }
    }
    return exData;

单元格为空可能会导致出现空值错误消息。您可以使用 OleDbDataReader.IsDbNull 方法

检查并防止错误消息