oledbdatareader中的行列没有数据

时间:2015-01-05 12:57:21

标签: c# sql excel

我尝试加载excel数据,使用oledbdatareader加载数据 这是我的代码

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

        }


        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())
                {
                    int nFields = reader.FieldCount;
                    ExcelData curLine = new ExcelData();
                    curLine.Actualkm = Convert.ToDecimal(reader[1]);
                    curLine.TRRequestID = reader[0].ToString();

                    curLine.Amount = Convert.ToDecimal(reader[2]);
                    exData.Add(curLine);
                }
                excel_con.Close();
                return Json(new { result = "success", data = exData });
          //  excel_con.Close();
        }
    }

我在curLine.Actualkm = Convert.ToDecimal(reader 1);

中收到错误

这是我的吸气鬼和二传手

      public class ExcelData
    {
        private string _TRRequestID;

        public string TRRequestID
        {
            get { return _TRRequestID; }
            set { _TRRequestID = value; }
        }
        private decimal _Actualkm;

        public decimal Actualkm
        {
            get { return _Actualkm; }
            set { _Actualkm = value; }
        }
        private decimal _Amount;

        public decimal Amount
        {
            get { return _Amount; }
            set { _Amount = value; }
        }
    }

这是我的excel文件

enter image description here

请帮助我谢谢

1 个答案:

答案 0 :(得分:1)

代码正在尝试读取第11行。

我想你不需要空行,所以使用这个

if(!string.IsNullOrEmpty(reader [1] .ToString()){}

在你的使用代码中。