如何将excel表数据输入到c#中的LIST

时间:2015-01-05 11:26:22

标签: c# sql excel

我想将excel表值放到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();

之后

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

exData

这些是吸气剂和制定者

                 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; }
        }
    }

这里是虚拟excel表

enter image description here

请帮我解决这个问题

谢谢大家。

1 个答案:

答案 0 :(得分:1)

如果要返回List<ExcelData>,则无需加载DataTable。

有效地,DataAdapter.Fill方法使用内部OleDbDataReader循环返回的数据并填充DataTable。现在,如果要返回List<ExcelData>,则需要在表上再次循环,并为表中的每一行构建一个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方法

检查并阻止错误消息