http://www.cnblogs.com/Jin-1007/archive/2012/04/24/2468129.html
C# list导出Excel(二)
public string CreateAdvExcel(IList<DocAdvInfo> lt)
{
StringBuilder builder = new StringBuilder();
Random rn = new Random();
string name = rn.Next(9999) + ".xls";
string path = Server.MapPath("\\Document\\" + name);
System.Reflection.PropertyInfo[] myPropertyInfo = lt.First().GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
int i = 0, j;
for (i = 0, j = myPropertyInfo.Length; i < j; i++)
{
System.Reflection.PropertyInfo pi = myPropertyInfo[i];
string headname = pi.Name;//单元格头部
builder.Append(headname);
builder.Append("\t");
}
builder.Append("\n");
foreach (DocAdvInfo t in lt)
{
if (lt == null)
{
continue;
}
for (i = 0, j = myPropertyInfo.Length; i < j; i++)
{
System.Reflection.PropertyInfo pi = myPropertyInfo[i];
string str = string.Format("{0}", pi.GetValue(t, null)).Replace("\n", "");
if (str == "")
{
builder.Append("\t");
}
else
{
builder.Append(str + "\t");//横向跳到另一个单元格
}
}
builder.Append("\n");//换行
}
StreamWriter sw = new StreamWriter(path, false, System.Text.Encoding.GetEncoding("GB2312"));
sw.Write(builder.ToString());//输出
sw.Flush();
sw.Close();

本文介绍了一种使用C#将List<DocAdvInfo>类型的数据导出为Excel文件的方法。通过反射获取对象属性并将其写入到Excel单元格中。此方法适用于批量数据导出场景。
5673

被折叠的 条评论
为什么被折叠?



