我正在尝试上传一个 csv 文件并使用 MVC3 实现 CSVHelper 主管。
https://github.com/JoshClose/CsvHelper
我还没有找到将其与文件上传一起使用的示例。基本上,我需要获取 CSV 文件并映射到实体对象并保存到数据库。这是我的实体:
public class SurveyEmailListModels
{
[Key]
public int SurveyEmailListId { get; set; }
[CsvField(Index = 0)]
public int ProgramId { get; set; }
[CsvField(Index = 1)]
public virtual SurveyProgramModels SurveyProgramModels { get; set; }
[CsvField(Index = 2)]
public string SurveyEmailAddress { get; set; }
[CsvField(Index = 3)]
public bool SurveyResponded { get; set; }
}
上传处理程序:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, SurveyEmailListModels surveyemaillistmodels, int id)
{
if (file != null && file.ContentLength > 0)
{
// Collect file and place into directory for source file download
var appData = Server.MapPath("~/csv/");
var filename = Path.Combine(appData, Path.GetFileName(file.FileName));
file.SaveAs(filename);
// surveyemaillistmodels.SurveyEmailAddress = "test@test.com";
// surveyemaillistmodels.SurveyResponded = true;
// surveyemaillistmodels.ProgramId = id;
db.SurveyEmailListModels.Add(surveyemaillistmodels);
db.SaveChanges();
return Content(filename);
}
return Json(true);
}
我不确定如何遍历 CSV 文件并保存到数据库。有人有例子吗?