ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2022-08-24 15:01:08  阅读:263  来源: 互联网

标签:cell string C# 乱码 whereQuery strLine new csv Response


  • /// <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);
  • }
  • }

标签:cell,string,C#,乱码,whereQuery,strLine,new,csv,Response
来源: https://www.cnblogs.com/cuihongyu3503319/p/16619935.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有