MyXls导出实体类集合

using org.in2bits.MyXls;
using System.Collections.Generic;
using System.Reflection;
------------------------------------------------------------
List<UserInfo> rows = GetUserList();
ExportExcel(rows, "UserInfoDoc", "UserInfoList");

//ExportExcel(rows, "", "");
------------------------------------------------------------
private void ExportExcel<T>(List<T> items, string FileName, string SheetName, params string[] titles)
{
    #region 检查数据
    if (items.Count <= 0) return;
    PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
    if (properties.Length <= 0) return;
    #endregion

    #region 文档信息
    XlsDocument doc = new XlsDocument();
    Worksheet sheet;
    if (string.IsNullOrEmpty(FileName))
        doc.FileName = typeof(T).Name + "_" + DateTime.Now.ToString("yyyy.MM.dd.HH.mm.ss") + ".XLS";  //实体类类名
    else doc.FileName = FileName + "_" + DateTime.Now.ToString("yyyy.MM.dd.HH.mm.ss") + ".XLS";
    if (string.IsNullOrEmpty(SheetName))
        sheet = doc.Workbook.Worksheets.AddNamed(typeof(T).Name + "List");
    else sheet = doc.Workbook.Worksheets.AddNamed(SheetName);
    #endregion

    #region 设置标题
    if (titles.Length > 0)
    {
        for (int i = 0; i < titles.Length; i++)
        {
            sheet.Cells.AddValueCell(1, i + 1, titles[i]);
        }
    }
    else
    {
        for (int i = 0; i < properties.Length; i++)
        {
            sheet.Cells.AddValueCell(1, i + 1, properties[i].Name);  //属性名
        }
    }
    #endregion

    #region 生成内容
    int rowNum = 1;
    for (int i = 0; i < items.Count; i++)  //历遍实体类集合
    {
        rowNum++;  //第二行开始
        int colNum = 1;  //第一列开始
        foreach (PropertyInfo info in properties)  //历遍实体属性
        {
            string name = info.Name;
            object value = info.GetValue(items[i], null);
            if (info.PropertyType.IsValueType || info.PropertyType.Name.StartsWith("String"))
            {
                sheet.Cells.AddValueCell(rowNum, colNum++, value.ToString());
            }
        }
    }
    #endregion

    #region 文档输出
    try
    {
        doc.Send();
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }
    catch { }
    #endregion
}

 

你可能感兴趣的:(xls)