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

2022/8/25 1:23:05

本文主要是介绍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);
  • }
  • }

                   

这篇关于C#下载csv代码总结(解决中文乱码问题)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程