----------------------DownloadCSVAsStreame<T>(IList<T> param, string sheetname = null) where T : new()----------------
基础依据:
CSV格式为
cell1,cell2,cell3
cell1,cell2,cell3
注意:
CSV是用符号分割cell和Row的,所以必须在必要的解决Data中存在于现有字符冲突的其他字符,如英文符号【"】,【,】,【 】,【 】,【 】等
::::RemoveWrap这里RemoveWrap的作用就是去除空字符,和替换敏感字符,以防止CSV导出后布局混乱。
-------------------------------------------------------------------------------------------------------------------------------
1 public static MemoryStream DownloadCSVAsStreame<T>(IList<T> param, string sheetname = null) where T : new() 2 { 3 if (param == null || param.Count < 1) 4 return null; 5 int rowsCount = param.Count(), columnCount = param.FirstOrDefault().GetType().GetProperties().Count(p => p.PropertyType.IsPublic); 6 var tp = typeof(T); 7 var tpattr = tp.GetCustomAttribute<JsonObjectAttribute>(); 8 if (tpattr == null) 9 return null; 10 StringBuilder sbcsv = new StringBuilder(); 11 List<PropertyInfo> pts = tp.GetProperties().Where(p => p.PropertyType.IsPublic).Select(o => o).ToList(); 12 string[] atv = pts.ConvertAll(ii => 13 { 14 var jsonPropertyAttribute = ii.GetCustomAttribute<JsonPropertyAttribute>(); 15 if (jsonPropertyAttribute != null) 16 return jsonPropertyAttribute.PropertyName; 17 return string.Empty; 18 }).ToArray(); 19 var me = new MemoryStream(); 20 int paddingrow = 0; 21 int rowindex = 0; 22 for (int nn = 0; nn < columnCount; nn++) 23 { 24 if (!string.IsNullOrEmpty(atv[nn])) 25 { 26 sbcsv.Append(RemoveWrap(atv[nn] ?? pts[nn].Name)).Append(","); 27 } 28 } 29 sbcsv.Remove(sbcsv.Length - 1, 1).Append(' ').Append(' '); 30 for (int r = 0; r < rowsCount; r++) 31 { 32 for (int pj = 0; pj < columnCount; pj++) 33 { 34 if (!string.IsNullOrEmpty(atv[pj])) 35 { 36 sbcsv.Append(RemoveWrap(pts[pj].GetValue(param[r]) != null 37 ? pts[pj].GetValue(param[r]).ToString() 38 : "")).Append(","); 39 } 40 } 41 sbcsv.Remove(sbcsv.Length - 1, 1).Append(' ').Append(' '); 42 } 43 sbcsv.Remove(sbcsv.Length - 2, 2); 44 var gbk=Encoding.GetEncoding("GB2312"); 45 var bts= gbk.GetBytes(sbcsv.ToString().ToArray()); 46 me.Write(bts,0,bts.Length); 47 return me; 48 } 49 50 private static string RemoveWrap(string sb) 51 { 52 return sb.Replace(",", ",").Replace(" ", " ").Replace(" ", " ").Replace(" ", " ").Replace(""","“").Replace(""", "“"); 53 }