zoukankan      html  css  js  c++  java
  • C# 利用NPOI把list导出为excel

    安装NPOI.Excel ,NPOI

    using System;
    using System.Collections.Generic;
    using System.DirectoryServices;
    using System.IO;
    using System.Reflection;
    using Newtonsoft.Json;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;

       
    public static void 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); PropertyInfo[] pis = type.GetProperties(); int pisLen = pis.Length - 2;//减2是多了2个外键引用 PropertyInfo pi = null; string displayName = string.Empty; while (piIndex < pisLen) { pi = pis[piIndex]; displayName = pi.Name; 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); while (piIndex < pisLen) { pi = pis[piIndex]; try { dataRow.CreateCell(piIndex).SetCellValue(pi.GetValue(data, null)?.ToString()); } catch (Exception) { dataRow.CreateCell(piIndex).SetCellValue(""); } piIndex++; } rowIndex++; } workbook.Write(ms); FileStream dumpFile = new FileStream(@"ur.xls", FileMode.Create, FileAccess.ReadWrite); ms.WriteTo(dumpFile); ms.Flush(); ms.Position = 0; dumpFile.Close(); }
  • 相关阅读:
    模式应用:自定义匹配
    WPF架构学习总结
    脑子是用来想事的,不是记事的
    参加峰会“金点子”的材料
    我所想的GIX4的权限
    Process, Thread, STA, MTA, COM object
    JAVA 游戏分享 “是男人就下100层”
    关于静态方法和实例方法的一些误区。
    软区域
    Dispose, Finalization, and Resource Management
  • 原文地址:https://www.cnblogs.com/cvol/p/14560538.html
Copyright © 2011-2022 走看看