Reputation: 923
Im try to load excel data to list here im using oledbdatareader to load the data here is my code
[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();
}
}
i get error in curLine.Actualkm = Convert.ToDecimal(reader1);
here is my getters and setters
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; }
}
}
here is my excel file
please help me thank you
Upvotes: 0
Views: 821
Reputation:
The code is trying to read the row 11.
I suppose you don't need the empty rows so use this
if(!string.IsNullOrEmpty(reader[1].ToString()) {}
in your using code.
Upvotes: 1