直接附上代碼
1 /// <summary> 2 /// 將List保存為Excel 3 /// </summary> 4 /// <typeparam name="T">保存的類類型</typeparam> 5 /// <param name="lt">需要保存的源數(shù)據(jù)</param> 6 /// <param name="fileName">保存的文件名稱</param> 7 /// <param name="fields">對應(yīng)于類的字段名稱</param> 8 /// <param name="titles">對應(yīng)于Excel的列名</param> 9 public static void Save<T>(List<T> lt, string fileName, string[] fields, string[] titles)10 {11 if (lt == null || lt.Count == 0)12 {13 throw new ArgumentNullException("數(shù)據(jù)為空");14 }15 16 var sb = new StringBuilder();17 PRopertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);18 const string next = "/t";19 20 foreach (var title in titles)21 {22 sb.Append(title).Append(next);23 }24 25 var propertys = new List<PropertyInfo>();26 27 foreach (var field in fields)28 {29 foreach (PropertyInfo prop in props)30 {31 if (prop.Name.Equals(field))32 {33 propertys.Add(prop);34 break;35 }36 }37 }38 39 sb.Append(Environment.NewLine);40 41 foreach (T item in lt)42 {43 foreach (var property in propertys)44 {45 object value = property.GetValue(item, null);46 47 if (property.PropertyType.BaseType == typeof(Enum))48 {49 sb.Append(GPMSKernel.Unility.Enums.GetEnumDescription(value));50 }51 else if (property.PropertyType == typeof(Boolean))52 {53 if ((bool)value)54 {55 sb.Append("是");56 }57 else58 {59 sb.Append("否");60 }61 }62 else63 {64 sb.Append(value);65 }66 67 sb.Append(next);68 }69 70 sb.Append(Environment.NewLine);71 }72 73 fileName = string.Format("{0}_{1}.xls", DateTime.Now.ToString("yyMMddHHmmss"), fileName);74 HttpContext.Current.Response.ContentType = "application/octet-stream";75 //通知瀏覽器下載文件而不是打開76 HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));77 HttpContext.Current.Response.BinaryWrite(Encoding.UTF8.GetBytes(sb.ToString()));78 HttpContext.Current.Response.Flush();79 HttpContext.Current.Response.End();80 }此方法是把List從Web服務(wù)器上下載到本地并保存為Excel的,其中l(wèi)t是要保存的數(shù)據(jù)源,fileName是對應(yīng)的文件名,可以直接寫為要保存的類名,
fields對應(yīng)于要保存的類的字段名,這個一定要正確,否則無法在類里找到該字段,titles是要保存的文件里面的列名,fields和titles必須一一對應(yīng),個數(shù)要相等。 保存之前有做特殊處理,比如如果要保存的類里面有枚舉的話,直接保存到Excel里會變成英文的,這一般不是用戶想看到的,那么需要在枚舉的每個值前面標(biāo)注[Description("***")],GPMSKernel.Unility.Enums.GetEnumDescription可以獲得枚舉的Description值;如果是布爾值的話,直接保存就變成了"True"或"False"了,我把這種轉(zhuǎn)換成了"是"或"否";如果要保存的類里面還有特殊的類,那么需要在這特殊的類里面重寫ToString方法,保存的時候?qū)凑赵揟oString方法保存....
新聞熱點(diǎn)
疑難解答
圖片精選