C#下载csv代码总结

一、C#导出csv格式代码如下:

  1         /// <summary>
  2         /// 下载
  3         /// </summary>
  4         /// <param name="startTime"></param>
  5         /// <param name="endTime"></param>
  6         public void Download(DateTime? startTime, DateTime? endTime)
  7         {
  8             Response<VSysLog> _rsp = new Response<VSysLog>();
  9             try
 10             {
 11                 using (NetEntities et = new NetEntities())
 12                 {
 13                     startTime = startTime == null ? DateTime.Now.AddMonths(-2) : startTime.Value;
 14                     endTime = endTime == null ? DateTime.Now : endTime.Value;
 15                     int deviceType = (int)EnumDeviceType.网关设备;
 16 
 17                     //搜索条件
 18                     var whereQuery = PredicateExtensions.True<net_warninglog>();
 19                     //搜索条件---开始时间和结束时间
 20                     whereQuery = whereQuery.And(n => n.WarningTime >= startTime && n.WarningTime <= endTime);
 21                     //搜索条件---设备类型
 22                     whereQuery = whereQuery.And(n => n.DeviecType == deviceType);
 23                     //搜索条件---模糊查询
 24                     if (!string.IsNullOrEmpty(Request["condition"]))
 25                     {
 26                         string condition = Request["condition"];
 27                         whereQuery = whereQuery.And(n => n.WarningSource.Contains(condition));
 28                     }
 29                     List<VWarningLog> logList = et.net_warninglog.Where(whereQuery.Compile()).AsEnumerable().Select(n =>
 30                                           new VWarningLog
 31                                           {
 32                                               id = n.ID,
 33                                               warningName = n.WarningName,
 34                                               warningReason = n.WarningReason,
 35                                               deviceType = Enum.GetName(typeof(EnumDeviceType), n.DeviecType),
 36                                               warningSource = n.WarningSource,
 37                                               descr = n.Descr,
 38                                               warningTime = n.WarningTime.ToString("yyyy-MM-dd HH:mm:ss")
 39                                           }).OrderByDescending(x => x.warningTime).ToList();
 40 
 41                     System.IO.StringWriter sw = new StringWriter();
 42                     StringBuilder sbTitle = new StringBuilder();
 43                     System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
 44                     //定义模版(标题、内容字段、格式化参数)
 45                     string[,] template = new string[,] {{ "终端编号,", "warningSource", "{0}"}, { "设备类型,", "deviceType", "{0}" }, { "报警原因,", "warningReason", "{0}"},
 46                                                                         { "报警信息,", "warningName", "{0}" }, { "描述", "descr", "{0}" }, { "报警时间", "warningTime", "{0}" } };
 47                     string strLine = "";
 48                     sw = new StringWriter();
 49                     //获取模板的行数
 50                     int colCount = template.GetLength(0);
 51                     //表头    
 52                     for (int i = 0; i < colCount; i++)
 53                     {
 54                         //在模板里面已经添加了逗号
 55                         strLine += template[i, 0];
 56                     }
 57                     strLine.Remove(strLine.Length - 1);
 58                     sw.WriteLine(strLine);
 59                     strLine = "";
 60 
 61                     //表的内容  
 62                     for (int j = 0; j < logList.Count; j++)
 63                     {
 64                         strLine = "";
 65                         for (int k = 0; k < colCount; k++)
 66                         {
 67                             if (k > 0 && k < colCount)
 68                             {
 69                                 strLine += ",";
 70                             }
 71                             string cell = "";
 72                             string data = string.Format(template[k, 2], logList[j].GetType().GetProperty(template[k, 1]).GetValue(logList[j], null));
 73                             if (string.IsNullOrEmpty(data))
 74                             {
 75                                 strLine += "";
 76                             }
 77                             else
 78                             {
 79                                 //前面加的单引号则是防止数字被转换成其它格式    
 80                                 cell = "'" + data.Trim();
 81                             }
 82                             //防止里面含有特殊符号
 83                             if (!string.IsNullOrEmpty(cell))
 84                             {
 85                                 cell = cell.Replace("\"", "\"\"");
 86                                 cell = "\"" + cell + "\"";
 87                                 strLine += cell;
 88                             }
 89                         }
 90                         sw.WriteLine(strLine);
 91                     }
 92                     string attachment = "attachment; filename=" + DateTime.Now.ToString("yyyy年MM月dd日HH点") + "网关报警日志.csv";
 93                     Response.Clear();
 94                     Response.ClearHeaders();
 95                     Response.ClearContent();
 96                     Response.AddHeader("content-disposition", attachment);
 97                     Response.ContentType = "text/csv";
 98                     Response.AddHeader("Pragma", "public");
 99                     Response.Charset = "UTF-8";
100                     Response.ContentEncoding = System.Text.Encoding.UTF8;
101                     Response.HeaderEncoding = System.Text.Encoding.UTF8;
102                     //防止中文乱码  
103                     Response.BinaryWrite(new byte[] { 0xEF, 0xBB, 0xBF });
104                     response.Write(sw.ToString());
105                     Response.End();
106                     sw.Close();
107                 }
108             }
109             catch (Exception ex)
110             {
111                 _rsp.code = (int)EnumCode.程序异常;
112                 _rsp.msg = ex.Message;
113                 LogHelper.WriteLog(className, "Download", ex);
114             }
115         }

仅作为保存,方便日后查看代码。

猜你喜欢

转载自www.cnblogs.com/jas0203/p/10364228.html
今日推荐