使用MVC和EF将CSV数据上载到SQL数据库

时间:2016-06-07 23:24:25

标签: c# asp.net-mvc entity-framework csv

我是新的MVC框架,并尝试弄清楚如何解析CSV文件,使得只有来自某些列的数据才会保存到数据库中。

我可以选择CSV文件并通过View上传,然后使用下面的代码将其传递给我的控制器Codelocker

public ActionResult UploadMultipleFiles(FileUploadViewModel fileModel)
{
    //open file
    if (Request.Files.Count == 1)
    {
        //get file
        var postedFile = Request.Files[0];
        if (postedFile.ContentLength > 0)
        {
            //read data from input stream
            using (var csvReader = new System.IO.StreamReader(postedFile.InputStream))
            {
                string inputLine = "";

                //read each line
                while ((inputLine = csvReader.ReadLine()) != null)
                {
                    //get lines values
                    string[] values = inputLine.Split(new char[] { ',' });

                    for (int x = 0; x < values.Length; x++)
                    {
                        //do something with each line and split value
                    }
                }

                csvReader.Close();
            }
        }
    }
    return View("Index");
}

但是,我不确定如何只在CSV文件中选择所需的列并将其存储到数据库中?

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

通过创建DataTable方法解决问题,方法是创建所需的列,然后使用StreamReader并循环遍历这些行并选择所需的列

[HttpPost]
public ActionResult UploadMultipleFiles()
{
    FileUploadService service = new FileUploadService();

    var postedFile = Request.Files[0];

    StreamReader sr = new StreamReader(postedFile.InputStream);
    StringBuilder sb = new StringBuilder();
    DataTable dt = CreateTable();
    DataRow dr;
    string s;
    int j = 0;

    while (!sr.EndOfStream)
    {
        while ((s = sr.ReadLine()) != null)
        {
            //Ignore first row as it consists of headers
            if (j > 0)
            {
                string[] str = s.Split(',');

                dr = dt.NewRow();
                dr["Postcode"] = str[0].ToString();
                dr["Latitude"] = str[2].ToString();
                dr["Longitude"] = str[3].ToString();
                dr["County"] = str[7].ToString();
                dr["District"] = str[8].ToString();
                dr["Ward"] = str[9].ToString();
                dr["CountryRegion"] = str[12].ToString();
                dt.Rows.Add(dr);
            }
            j++;
        }
    }
    service.SaveFilesDetails(dt);
    sr.Close();
    return View("Index");
}