首页 > 代码库 > C# 泛型List对象数据 导出 成 EXCEL数据表
C# 泛型List对象数据 导出 成 EXCEL数据表
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 }
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 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。