1,从数据库读取数据,然后导出CSV文件
[HttpPost] public FileResult ExportCSV() { var apps =。。。。//linq以及EF从数据库查询数据 MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); var csv = new CsvWriter(sw); foreach (var pp in apps) { csv.WriteField(0); //set to '0' csv.WriteField(""); //set empty space csv.WriteField("haha"); csv.NextRecord(); } sw.Flush(); ms.Position = 0; return File(ms, "text/comma-separated-values", "Export.csv"); }
2,页面上传CSV文件,服务器读取文件内容
@using (Html.BeginForm("ImportCSV", "ExportImport", FormMethod.Post, new { enctype = "multipart/form-data" })){}
[HttpPost] public JsonResult ImportCSV(HttpPostedFileBase csvToUpload) { using (var textReader = new StreamReader(csvToUpload.InputStream)) { var csv = new CsvReader(textReader); while (csv.Read()) { var field = csv.GetField(0); } } ....... }
参考: