天天看点

.net使用NPOI导出Excel封装

public static byte[] ExportToExcel<T>(List<T> modelList)
        {
            byte[] resultByte = null;

            IWorkbook workbook = new HSSFWorkbook();//创建Workbook对象
            ISheet sheet = workbook.CreateSheet();

            //填充表头
            IRow dataRow = sheet.CreateRow(0);
            System.Reflection.PropertyInfo[] ps = typeof(T).GetProperties();
            for (int i = 0; i < ps.Count(); i++)
            {
                //object obj = ps[i].GetValue(typeof(T), null);
                string name = ps[i].Name;
                dataRow.CreateCell(i).SetCellValue(name);
            }

            //填充内容
            for (int i = 0; i < modelList.Count; i++)
            {
                dataRow = sheet.CreateRow(i + 1);
                var type = modelList[i].GetType();
                ps = type.GetProperties();
                for (int j = 0; j < ps.Count(); j++)
                {
                    object obj = ps[j].GetValue(modelList[i], null);
                    if (obj != null)
                        dataRow.CreateCell(j).SetCellValue(obj.ToString());
                }
            }


            //保存
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                resultByte = ms.ToArray();
                ms.Dispose();
            }

            return resultByte;
        }

        /// <summary>
        /// 根据DateTable导出Excel
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static byte[] ExportToExcel(DataTable dt)
        {
            byte[] resultByte = null;

            IWorkbook workbook = new HSSFWorkbook();//创建Workbook对象
            ISheet sheet = workbook.CreateSheet();

            //填充表头
            IRow dataRow = sheet.CreateRow(0);

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                string name = dt.Columns[i].ColumnName;
                dataRow.CreateCell(i).SetCellValue(name);
            }

            //填充内容
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dataRow = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    object obj = dt.Rows[i][j];
                    if (obj != null)
                        dataRow.CreateCell(j).SetCellValue(obj.ToString());
                }
            }


            //保存
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                resultByte = ms.ToArray();
                ms.Dispose();
            }

            return resultByte;
        }