【问题标题】:Upload CSV data into SQL Database using MVC and EF使用 MVC 和 EF 将 CSV 数据上传到 SQL 数据库
【发布时间】:2016-06-07 23:24:24
【问题描述】:

我是新的 MVC 框架,并试图弄清楚如何以仅将某些列中的数据保存到数据库的方式解析 CSV 文件。

我可以选择 CSV 文件并通过视图将其上传并使用此处提到的以下代码将其传递给我的控制器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 文件中所需的列并将其存储到数据库中?

大家有什么建议吗?

【问题讨论】:

  • 您应该已经知道 CSV 文件的架构。通过使用values[x],您可以构建您的查询或根据特定列x 分配给您的数据库变量。
  • 这些 CSV 中平均有多少行?

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


【解决方案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");
}

【讨论】:

  • 既然是访问一个文件,那么应该考虑通过将同步动作方法转换为异步动作方法来将同步请求转换为异步请求。
  • 与答案无关,但您也可以查看此文件帮助程序库来处理处理文件的逻辑。 filehelpers.net
猜你喜欢
  • 2022-11-22
  • 2011-05-02
  • 1970-01-01
  • 1970-01-01
  • 2013-06-13
  • 1970-01-01
  • 1970-01-01
  • 2020-04-17
  • 2018-08-18
相关资源
最近更新 更多