C# list导出Excel(二)

上篇写的那个那个导出Excel的方法导出Excel的时间慢,后面想了个别的方法,导出Excel的时间很快

 1 public string CreateAdvExcel(IList<DocAdvInfo> lt)
 2         {
 3             StringBuilder builder = new StringBuilder();
 4             Random rn = new Random();
 5             string name = rn.Next(9999) + ".xls";
 6             string path = Server.MapPath("\\Document\\" + name);
 7             System.Reflection.PropertyInfo[] myPropertyInfo = lt.First().GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
 8             int i = 0, j;
 9             for (i = 0, j = myPropertyInfo.Length; i < j; i++)
10             {
11                 System.Reflection.PropertyInfo pi = myPropertyInfo[i];
12                 string headname = pi.Name;//单元格头部
13                 builder.Append(headname);
14                 builder.Append("\t");
15             }
16             builder.Append("\n");
17             foreach (DocAdvInfo t in lt)
18             {
19                 if (lt == null)
20                 {
21                     continue;
22                 }
23                 for (i = 0, j = myPropertyInfo.Length; i < j; i++)
24                 {
25                     System.Reflection.PropertyInfo pi = myPropertyInfo[i];
26                     string str = string.Format("{0}", pi.GetValue(t, null)).Replace("\n", "");
27                     if (str == "")
28                     {
29                         builder.Append("\t");
30                     }
31                     else
32                     {
33                         builder.Append(str + "\t");//横向跳到另一个单元格
34                     }
35                 }
36                 builder.Append("\n");//换行
37             }
38             StreamWriter sw = new StreamWriter(path, false, System.Text.Encoding.GetEncoding("GB2312"));
39             sw.Write(builder.ToString());//输出
40             sw.Flush();
41             sw.Close();
posted @ 2012-04-24 15:18  fycaijing  阅读(2931)  评论(0)    收藏  举报