C#调用NPOI组件导出Excel表格

把一个List集合的数据导出到Excel表格中

     public static string RenderToExcel<T>(List<T> datas)
        {
            MemoryStream ms = new MemoryStream();
            IWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("导出数据");
            IRow headerRow = sheet.CreateRow(0);

            int rowIndex = 1, piIndex = 0;
            Type type = typeof(T);
            var pis = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(i => i.PropertyType.IsValueType || i.PropertyType == typeof(string));

            string displayName = string.Empty;
            foreach (var pi in pis)
            {
                if (pi.GetCustomAttribute<NotExportAttribute>() != null)
                {
                    piIndex++;
                    continue;
                }
                //需要类反射出字段属性名
                displayName = pi.GetCustomAttribute<DisplayNameAttribute>().DisplayName;
                if (!displayName.Equals(string.Empty))
                {//如果该属性指定了DisplayName,则输出  
                    try
                    {
                        headerRow.CreateCell(piIndex).SetCellValue(displayName);
                    }
                    catch (Exception)
                    {
                        headerRow.CreateCell(piIndex).SetCellValue("");
                    }
                }
                piIndex++;
            }
            foreach (T data in datas)
            {
                piIndex = 0;
                IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (var pi in pis)
                {
                    if (pi.GetCustomAttribute<NotExportAttribute>() != null)
                    {
                        piIndex++;
                        continue;
                    }
                    try
                    {
                        dataRow.CreateCell(piIndex).SetCellValue(pi.GetValue(data, null).ToString());
                    }
                    catch (Exception)
                    {
                        dataRow.CreateCell(piIndex).SetCellValue("");
                    }
                    piIndex++;
                }
                rowIndex++;
            }
            workbook.Write(ms);
            string strFileName = Guid.NewGuid().ToString() + ".xls";
            string strFilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\ExcelFile\\" + strFileName; ; //Server.MapPath("ExcelFile\\") + "\\" + System.DateTime.Now.ToString() + ".xls";
            FileStream dumpFile = new FileStream(strFilePath, FileMode.Create, FileAccess.ReadWrite);
            ms.WriteTo(dumpFile);
            ms.Flush();
            ms.Position = 0;
            dumpFile.Close();
            return strFileName;
        }

上面代码中第一个foreach是遍历list中类型的特性并获取给特性中的内容,作为Excel表格的第一行内容

第二个foreach遍历list列表中的数据填充到Excel表格下面

然后保存这个Excel

其中需要创建NotExportAttribute类

    [AttributeUsage(AttributeTargets.Property)]
    public class NotExportAttribute : Attribute
    {
     }

数据实体需要加上DisplayName特性

    public class Student
    {
        [DisplayName("学生的ID")]
        public int StudentID { get; set; }
        [DisplayName("学生姓名")]
        public string Name { get; set; }
        [DisplayName("学生的年龄")]
        public int Age { get; set; }
        /// <summary>
        /// 1男2女3未设置
        /// </summary>
        [DisplayName("学生的性别")]
        public int Gender { get; set; }

    }

 

转载于:https://www.cnblogs.com/ansheng/p/5457712.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值