zoukankan      html  css  js  c++  java
  • 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; }
    
        }
  • 相关阅读:
    恕我直言,你可能误解了微服务
    准备情人节礼物比写代码难?来看看IT直男给女友们的礼物
    2019年微服务5大趋势,你pick哪个?
    拼多多通用优惠券漏洞被薅羊毛数千万 你的系统有反作弊防护吗?
    知物由学 | AI在Facebook清理有害内容上扮演了什么角色?
    打造业界最牛微服务,网易云这两位“大神”获了大奖
    网易云轻舟微服务斩获“创新产品奖”等两项大奖
    GIS中栅格数据结构的显示与计算
    未能找到tempselect2.cur的一部分
    地图下载3之超图瓦片下载工具
  • 原文地址:https://www.cnblogs.com/ansheng/p/5457712.html
Copyright © 2011-2022 走看看