.netMVC-下载CSV格式的文件到本地
需求:在本次开发中,有一项任务是将数据库中的各种数据导出为csv格式的文件。
大致思路:声明文件名,声明文件的路径。路径名+文件名就得到了文件的全路径。使用写入器(StreamWrite)向文件写入数据,在写入表格类型的文件前,先将列名写入(sw.Write();)再依次写入其他数据
当我们输出的文件是CSV格式的表格文件时,写入的每个单元格之间只用“,”隔开。
通过Post方法得到文件,返回File类型的结果对象,就会通过浏览器下载到本地内存中。
[HttpPost] public ActionResult ImportRWPData(GridSearchEx gridSearch) { //通过自定义方法从数据库中拿到的数据 List<Task> tasks = GetRWPDataSearch(gridSearch).ToList(); if (tasks.Count == 0) { ViewBag.RWPError = "信息: 未找到匹配的RWP信息"; gridSearch.ShowClearButton = false; gridSearch.SearchText = "导出"; SetSearchOptions(gridSearch, 3, ImportRWPDataGroup); return View(); }
//设置文件的物理路径和文件名称
//Server:获取Http服务器对象
//Server.MapPath:返回服务器上指定的虚拟路径相对应的物理文件路径
//System.web.HttpContext.Current.Request.ApplicationPath:获取服务器上当前应用程序的虚拟应用程序根路径 string fileName = "RWP" + DateTime.Now.Day.ToString(CultureInfo.InvariantCulture) + DateTime.Now.Hour.ToString(CultureInfo.InvariantCulture)
+ DateTime.Now.Minute.ToString(CultureInfo.InvariantCulture)
+ DateTime.Now.Second.ToString(CultureInfo.InvariantCulture) + ".csv"; string file = Path.Combine(Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath), "Exports/" + fileName); //根据从数据库中拿到的数据集合以及创建好的文件的全路径,创建文件
CreateRWPCSVFile(tasks, file);
//最后返回的是文件流结果对象 return File(file, "text/plain", fileName); }
private void CreateRWPCSVFile(List<Task> tasks, string file) { List<string> Columns = new List<string>(); Columns.Add("TaskNo"); Columns.Add("TaskName"); Columns.Add("TaskDesc"); Columns.Add("Enabled"); Columns.Add("PermitTypeID"); Columns.Add("AreaDescription"); Columns.Add("LocationCode"); Columns.Add("Identifier"); Columns.Add("Startdate"); Columns.Add("ExpiryDate"); Columns.Add("RiskLevelID"); Columns.Add("WorkTypeID"); Columns.Add("DefaultDeepDoseLimit"); Columns.Add("DefaultDeepDoseRateLimit"); Columns.Add("DefaultManWorkedTimeLimit");
//String.Join():给Columns中的每个元素添加","号,返回字符串 string ColulmnsString = string.Join(",", Columns);
//创建写入流 using (StreamWriter sw = new StreamWriter(file, false, Encoding.UTF8)) //创建文件 { //sw.AutoFlush = true; sw.WriteLine(ColulmnsString); _db.Configuration.ProxyCreationEnabled = false; List<AlaraPermitType> permitTypes = _db.AlaraPermitTypes.ToList(); List<AlaraArea> areas = _db.AlaraAreas.ToList(); List<DataDic> dataDics = _db.DataDics.ToList(); foreach (var task in tasks) { string permitType = permitTypes.FirstOrDefault(p =>task.PermitTypeID!=null && p.PermitTypeID == (long)task.PermitTypeID)?.Description; string areaDescription = areas.FirstOrDefault(a => task.AreaId != null && a.AreaID == (Guid)task.AreaId)?.AreaDescription; string locationCode = areas.FirstOrDefault(a => task.AreaId != null && a.AreaID == (Guid)task.AreaId)?.LocationCode; string riskLevel = dataDics.FirstOrDefault(d => task.RiskLevelID != null && d.Type == "RiskLevel" && d.ID == int.Parse(task.RiskLevelID.ToString())).Name; string workType = dataDics.FirstOrDefault(d => task.WorkTypeID != null && d.Type == "WorkType" && d.ID == int.Parse(task.RiskLevelID.ToString())).Name; sw.Write($"{task.TaskNo},"); sw.Write($"{task.TaskName},"); sw.Write($"{task.TaskDesc},"); sw.Write($"{task.Enabled},"); sw.Write($"{permitType},"); sw.Write($"{areaDescription},"); sw.Write($"{locationCode},"); sw.Write($"{task.Identifier},"); sw.Write($"{task.Startdate},"); sw.Write($"{task.ExpiryDate},"); sw.Write($"{riskLevel},"); sw.Write($"{workType},"); sw.Write($"{task.DefaultDeepDoseLimit},"); sw.Write($"{task.DefaultDeepDoseRateLimit},"); sw.Write($"{task.DefaultManWorkedTimeLimit}\r\n"); //写完一个对象后换行写下一个对象 sw.Flush(); } } }