• 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; }
    
        }
  • 相关阅读:
    数据结构中的图面试题总结
    大数运算
    页面置换算法
    栈的效率为什么比堆高?
    C#获取FTP文件详细备注信息
    WPF DataGrid_SelectChanged获取单元内容
    Python datetime模块参考手册
    Linux下使用 virtualenv 虚拟独立 Python 环境
    Jupyter Notebook 快捷键使用指南
    IPython 基本使用
  • 原文地址:https://www.cnblogs.com/ansheng/p/5457712.html
Copyright © 2020-2023  润新知