C#使用NPOI导出Excel类封装
时间:2022-08-09 08:32:00|栏目:.NET代码|点击: 次
NPOI是指构建在POI 3.x版本之上的一个程序,NPOI可以在没有安装Office的情况下对Word或Excel文档进行读写操作。 NPOI是一个开源的C#读写Excel、WORD等微软OLE2组件文档的项目。
以下代码主要分3部分:通过实体类的自定义特性导出Excel文件
1、封装类:ExcelHelper
2、实体类:StudentModel
3、调用:Form1
ExcelHelper
/// <summary> /// Excel操作类 /// </summary> /// <typeparam name="T">实体类</typeparam> public class ExcelHelper<T> where T : class { /// <summary> /// 保存Excel文件 /// </summary> /// <param name="excelName">Excel文件名</param> /// <param name="sheetName">Sheet工作表名</param> /// <param name="data">实体类对象</param> public static void SaveExcelFile(string excelName, string sheetName, List<T> data) { IWorkbook workBook = new HSSFWorkbook(); //创建一个Excel文档 ISheet sheet = workBook.CreateSheet(sheetName); //创建一个工作表Sheet int rowNum = 0; var row = sheet.CreateRow(sheet.LastRowNum); //LastRowNum记录当前可用写入的行索引 PropertyInfo[] preInfo = typeof(T).GetProperties();//获取这个实体对象的所有属性 foreach (var item in preInfo) { object[] objPres = item.GetCustomAttributes(typeof(DescriptionAttribute), true);//获取当前属性的自定义特性列表 if (objPres.Length > 0) { for (int i = 0; i < objPres.Length; i++) { row.CreateCell(rowNum).SetCellValue(((DescriptionAttribute)objPres[i]).Description);//创建行,将当前自定义特性写入 rowNum++;//行索引加1,下次往后一格创建行 } } } int j = sheet.LastRowNum + 1, columnNum = 0; foreach (var item in data) { columnNum = 0; row = sheet.CreateRow(j++); var itemProps = item.GetType().GetProperties(); //获取当前对象的属性列表 foreach (var itemPropSub in itemProps) { //获取当前对象特性中的自定义特性[Description("自定义特性")] var objs = itemPropSub.GetCustomAttributes(typeof(DescriptionAttribute), true); if (objs.Length > 0) { //将当前对象的特性值,插入当前行的第n列单元格 row.CreateCell(columnNum).SetCellValue(itemPropSub.GetValue(item, null) == null ? "" : itemPropSub.GetValue(item, null).ToString()); columnNum++; } } } //文件流写入 using (MemoryStream ms = new MemoryStream()) { workBook.Write(ms); using (FileStream fs = new FileStream(excelName, FileMode.Create, FileAccess.Write)) { ms.WriteTo(fs); } ms.Flush(); ms.Position = 0; workBook.Close(); } } }
StudentModel
//实体类 public class StudentModel { [Description("学号")] public string ID { get; set; } [Description("姓名")] public string Name { get; set; } [Description("年龄")] public string Age { get; set; } [Description("性别")] public string Six { get; set; } [Description("地址")] public string Address { get; set; } [Description("电话")] public string Tel { get; set; } }
调用:
List<StudentModel> stdList = new List<StudentModel>(); stdList.Add(new StudentModel() { ID = "001", Name = "Peter", Age = "26", Six = "男", Address = "东京", Tel = "123456789" }); stdList.Add(new StudentModel() { ID = "002", Name = "Jerry", Age = "36", Six = "男", Address = "首尔", Tel = "987654321" }); ExcelHelper<StudentModel>.SaveExcelFile(Application.StartupPath + "\\StudentInfo.xls", "Student", stdList);
结果: