• 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
    }

  • 相关阅读:
    CSS的display小记
    Oracle PL/SQL中的循环处理(sql for循环)
    Windows下Git服务器搭建及使用过程中的一些问题
    IIS故障问题(Connections_Refused)分析及处理
    [转载]Function.apply and Function.call in JavaScript
    CentOS中文乱码问题的解决方法
    sed之G、H、g、h使用
    Linux命令:chgrp chown chmod
    javascirpt倒计时
    linux:sed高级命令之n、N
  • 原文地址:https://www.cnblogs.com/vipcjob/p/1760499.html
Copyright © 2020-2023  润新知