C#下载csv代码总结(解决中文乱码问题)


  • /// <summary>
  • /// 下载
  • /// </summary>
  • /// <param name=”startTime”></param>
  • /// <param name=”endTime”></param>
  • public void Download(DateTime? startTime, DateTime? endTime)
  • {
  • Response<VSysLog> _rsp = new Response<VSysLog>();
  • try
  • {
  • using (NetEntities et = new NetEntities())
  • {
  • startTime = startTime == null ? DateTime.Now.AddMonths(-) : startTime.Value;
  • endTime = endTime == null ? DateTime.Now : endTime.Value;
  • int deviceType = (int)EnumDeviceType.网关设备;
  •  
  • //搜索条件
  • var whereQuery = PredicateExtensions.True<net_warninglog>();
  • //搜索条件—开始时间和结束时间
  • whereQuery = whereQuery.And(n => n.WarningTime >= startTime && n.WarningTime <= endTime);
  • //搜索条件—设备类型
  • whereQuery = whereQuery.And(n => n.DeviecType == deviceType);
  • //搜索条件—模糊查询
  • if (!string.IsNullOrEmpty(Request[“condition”]))
  • {
  • string condition = Request[“condition”];
  • whereQuery = whereQuery.And(n => n.WarningSource.Contains(condition));
  • }
  • List<VWarningLog> logList = et.net_warninglog.Where(whereQuery.Compile()).AsEnumerable().Select(n =>
  • new VWarningLog
  • {
  • id = n.ID,
  • warningName = n.WarningName,
  • warningReason = n.WarningReason,
  • deviceType = Enum.GetName(typeof(EnumDeviceType), n.DeviecType),
  • warningSource = n.WarningSource,
  • descr = n.Descr,
  • warningTime = n.WarningTime.ToString(“yyyy-MM-dd HH:mm:ss”)
  • }).OrderByDescending(x => x.warningTime).ToList();
  •  
  • System.IO.StringWriter sw = new StringWriter();
  • StringBuilder sbTitle = new StringBuilder();
  • System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
  • //定义模版(标题、内容字段、格式化参数)
  • string[,] template = new string[,] {{ “终端编号,”, “warningSource”, “{0}”}, { “设备类型,”, “deviceType”, “{0}” }, { “报警原因,”, “warningReason”, “{0}”},
  • { “报警信息,”, “warningName”, “{0}” }, { “描述”, “descr”, “{0}” }, { “报警时间”, “warningTime”, “{0}” } };
  • string strLine = “”;
  • sw = new StringWriter();
  • //获取模板的行数
  • int colCount = template.GetLength();
  • //表头
  • for (int i = ; i < colCount; i++)
  • {
  • //在模板里面已经添加了逗号
  • strLine += template[i, ];
  • }
  • strLine.Remove(strLine.Length – );
  • sw.WriteLine(strLine);
  • strLine = “”;
  •  
  • //表的内容
  • for (int j = ; j < logList.Count; j++)
  • {
  • strLine = “”;
  • for (int k = ; k < colCount; k++)
  • {
  • if (k > && k < colCount)
  • {
  • strLine += “,”;
  • }
  • string cell = “”;
  • string data = string.Format(template[k, ], logList[j].GetType().GetProperty(template[k, ]).GetValue(logList[j], null));
  • if (string.IsNullOrEmpty(data))
  • {
  • strLine += “”;
  • }
  • else
  • {
  • //前面加的单引号则是防止数字被转换成其它格式
  • cell = “‘” + data.Trim();
  • }
  • //防止里面含有特殊符号
  • if (!string.IsNullOrEmpty(cell))
  • {
  • cell = cell.Replace(“/””, “/”/””);
  • cell = “/”” + cell + “/””;
  • strLine += cell;
  • }
  • }
  • sw.WriteLine(strLine);
  • }
  • string attachment = “attachment; filename=” + DateTime.Now.ToString(“yyyy年MM月dd日HH点”) + “网关报警日志.csv”;
  • Response.Clear();
  • Response.ClearHeaders();
  • Response.ClearContent();
  • Response.AddHeader(“content-disposition”, attachment);
  • Response.ContentType = “text/csv”;
  • Response.AddHeader(“Pragma”, “public”);
  • Response.Charset = “UTF-8”;
  • Response.ContentEncoding = System.Text.Encoding.UTF8;
  • Response.HeaderEncoding = System.Text.Encoding.UTF8;
  • //防止中文乱码(解决中文乱码问题)
  • Response.BinaryWrite(new byte[] { 0xEF, 0xBB, 0xBF });
  • response.Write(sw.ToString());
  • Response.End();
  • sw.Close();
  • }
  • }
  • catch (Exception ex)
  • {
  • _rsp.code = (int)EnumCode.程序异常;
  • _rsp.msg = ex.Message;
  • LogHelper.WriteLog(className, “Download”, ex);
  • }
  • }

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/282026.html

(0)
上一篇 2022年8月24日
下一篇 2022年8月24日

相关推荐

发表回复

登录后才能评论