標籤:style blog http color os 檔案 資料 io
1 /// <summary>
2 /// 將一組對象匯出成EXCEL
3 /// </summary>
4 /// <typeparam name="T">要匯出對象的類型</typeparam>
5 /// <param name="objList">一組對象</param>
6 /// <param name="FileName">匯出後的檔案名稱</param>
7 /// <param name="columnInfo">列名資訊</param>
8 public void ListToExcel<T>(List<T> objList, string FileName, Dictionary<string, string> columnInfo)
9 {
10 if (columnInfo.Count == 0) { return; }
11 if (objList.Count == 0) { return; }
12 //產生EXCEL的HTML
13 string excelStr = "";
14 Type myType = objList[0].GetType();
15 //根據反射從傳遞進來的屬性名稱資訊得到要顯示的屬性
16 List<System.Reflection.PropertyInfo> myPro = new List<System.Reflection.PropertyInfo>();
17 foreach (string cName in columnInfo.Keys)
18 {
19 System.Reflection.PropertyInfo p = myType.GetProperty(cName);
20 if (p != null)
21 {
22 myPro.Add(p);
23 excelStr += columnInfo[cName] + "\t";
24 }
25 }
26 //如果沒有找到可用的屬性則結束
27 if (myPro.Count == 0) { return; }
28 excelStr += "\n";
29 foreach (T obj in objList)
30 {
31 foreach (System.Reflection.PropertyInfo p in myPro)
32 {
33 excelStr += p.GetValue(obj, null) + "\t";
34 }
35 excelStr += "\n";
36 }
37 //輸出EXCEL
38 HttpResponse rs = System.Web.HttpContext.Current.Response;
39 rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
40 rs.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
41 rs.ContentType = "application/ms-excel";
42 rs.Write(excelStr);
43 rs.End();
44 }View Code