当前位置: 首页 > news >正文

List导出到Excel文件

例如用户列表导出

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Admin.Web.Controllers;
using Business.OrganizationManage;
using Entity.OrganizationManage;
using Model.Param.OrganizationManage;
using Util;
using Util.Model;namespace Admin.Web.Areas.OrganizationManage.Controllers
{[Area("OrganizationManage")]public class UserController : BaseController{private UserBLL userBLL = new UserBLL();[HttpPost]public async Task<IActionResult> ExportUserJson(UserListParam param){TData<string> obj = new TData<string>();TData<List<UserEntity>> userObj = await userBLL.GetList(param);if (userObj.Tag == 1){string file = new ExcelHelper<UserEntity>().ExportToExcel("用户列表.xls","用户列表",userObj.Data,new string[] { "UserName", "RealName", "Gender", "Mobile", "Email" });obj.Data = file;obj.Tag = 1;}return Json(obj);}}
}

用户实体类

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;namespace Entity.OrganizationManage
{[Table("SysUser")]public class UserEntity : BaseExtensionEntity{[Description("用户名")]public string UserName { get; set; }public string Password { get; set; }[JsonIgnore]public string Salt { get; set; }[Description("真实姓名")]public string RealName { get; set; }[Description("性别")]public int? Gender { get; set; }public string Birthday { get; set; }public string Portrait { get; set; }public string Email { get; set; }[Description("手机号")]public string Mobile { get; set; }public string QQ { get; set; }public string Wechat { get; set; }public int? LoginCount { get; set; }public int? UserStatus { get; set; }/// <summary>/// 角色Id/// </summary>[NotMapped]public string RoleIds { get; set; }}
}

ExportToExcel方法如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;namespace Util
{/// <summary>/// List导出到Excel文件/// </summary>/// <typeparam name="T"></typeparam>public class ExcelHelper<T> where T : new(){#region List导出到Excel文件/// <summary>/// List导出到Excel文件/// </summary>/// <param name="sFileName"></param>/// <param name="sHeaderText"></param>/// <param name="list"></param>public string ExportToExcel(string sFileName, string sHeaderText, List<T> list, string[] columns){sFileName = string.Format("{0}_{1}", SecurityHelper.GetGuid(), sFileName);string sRoot = GlobalContext.HostingEnvironment.ContentRootPath;string partDirectory = string.Format("Resource{0}Export{0}Excel", Path.DirectorySeparatorChar);string sDirectory = Path.Combine(sRoot, partDirectory);string sFilePath = Path.Combine(sDirectory, sFileName);if (!Directory.Exists(sDirectory)){Directory.CreateDirectory(sDirectory);}using (MemoryStream ms = CreateExportMemoryStream(list, sHeaderText, columns)){using (FileStream fs = new FileStream(sFilePath, FileMode.Create, FileAccess.Write)){byte[] data = ms.ToArray();fs.Write(data, 0, data.Length);fs.Flush();}}return partDirectory + Path.DirectorySeparatorChar + sFileName;}/// <summary>  /// List导出到Excel的MemoryStream  /// </summary>  /// <param name="list">数据源</param>  /// <param name="sHeaderText">表头文本</param>  /// <param name="columns">需要导出的属性</param>  private MemoryStream CreateExportMemoryStream(List<T> list, string sHeaderText, string[] columns){HSSFWorkbook workbook = new HSSFWorkbook();ISheet sheet = workbook.CreateSheet();Type type = typeof(T);PropertyInfo[] properties = ReflectionHelper.GetProperties(type, columns);ICellStyle dateStyle = workbook.CreateCellStyle();IDataFormat format = workbook.CreateDataFormat();dateStyle.DataFormat = format.GetFormat("yyyy-MM-dd");//单元格填充循环外设定单元格格式,避免4000行异常ICellStyle contentStyle = workbook.CreateCellStyle();contentStyle.Alignment = HorizontalAlignment.Left;contentStyle.WrapText = true;contentStyle.VerticalAlignment = VerticalAlignment.Center;#region 取得每列的列宽(最大宽度)int[] arrColWidth = new int[properties.Length];for (int columnIndex = 0; columnIndex < properties.Length; columnIndex++){//GBK对应的code page是CP936arrColWidth[columnIndex] = properties[columnIndex].Name.Length;}#endregionfor (int rowIndex = 0; rowIndex < list.Count; rowIndex++){#region 新建表,填充表头,填充列头,样式if (rowIndex == 65535 || rowIndex == 0){if (rowIndex != 0){sheet = workbook.CreateSheet();}#region 表头及样式{IRow headerRow = sheet.CreateRow(0);headerRow.HeightInPoints = 25;headerRow.CreateCell(0).SetCellValue(sHeaderText);ICellStyle headStyle = workbook.CreateCellStyle();headStyle.Alignment = HorizontalAlignment.Center;IFont font = workbook.CreateFont();font.FontHeightInPoints = 20;font.Boldweight = 700;headStyle.SetFont(font);headerRow.GetCell(0).CellStyle = headStyle;sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, properties.Length - 1));}#endregion#region 列头及样式{IRow headerRow = sheet.CreateRow(1);ICellStyle headStyle = workbook.CreateCellStyle();headStyle.Alignment = HorizontalAlignment.Center;IFont font = workbook.CreateFont();font.FontHeightInPoints = 10;font.Boldweight = 700;headStyle.SetFont(font);for (int columnIndex = 0; columnIndex < properties.Length; columnIndex++){// 类属性如果有Description就用Description当做列名DescriptionAttribute customAttribute = (DescriptionAttribute)Attribute.GetCustomAttribute(properties[columnIndex], typeof(DescriptionAttribute));string description = properties[columnIndex].Name;if (customAttribute != null){description = customAttribute.Description;}headerRow.CreateCell(columnIndex).SetCellValue(description);headerRow.GetCell(columnIndex).CellStyle = headStyle;//根据表头设置列宽  sheet.SetColumnWidth(columnIndex, (arrColWidth[columnIndex] + 1) * 256);}}#endregion}#endregion#region 填充内容IRow dataRow = sheet.CreateRow(rowIndex + 2); // 前面2行已被占用for (int columnIndex = 0; columnIndex < properties.Length; columnIndex++){ICell newCell = dataRow.CreateCell(columnIndex);newCell.CellStyle = contentStyle;string drValue = properties[columnIndex].GetValue(list[rowIndex], null).ParseToString();//根据单元格内容设定列宽int length = (System.Text.Encoding.UTF8.GetBytes(drValue).Length + 1) * 256;//超出固定宽度,按固定宽度显示(上面已设置自动换行)(注意:POI 把 列宽 > 255 视为非法值,会抛异常;)if (length > 120 * 256){length = 120 * 256;}if (sheet.GetColumnWidth(columnIndex) < length && !drValue.IsEmpty()){sheet.SetColumnWidth(columnIndex, length);}switch (properties[columnIndex].PropertyType.ToString()){case "System.String":newCell.SetCellValue(drValue);break;case "System.DateTime":case "System.Nullable`1[System.DateTime]":newCell.SetCellValue(drValue.ParseToDateTime());newCell.CellStyle = dateStyle; //格式化显示  break;case "System.Boolean":case "System.Nullable`1[System.Boolean]":newCell.SetCellValue(drValue.ParseToBool());break;case "System.Byte":case "System.Nullable`1[System.Byte]":case "System.Int16":case "System.Nullable`1[System.Int16]":case "System.Int32":case "System.Nullable`1[System.Int32]":newCell.SetCellValue(drValue.ParseToInt());break;case "System.Int64":case "System.Nullable`1[System.Int64]":newCell.SetCellValue(drValue.ParseToString());break;case "System.Double":case "System.Nullable`1[System.Double]":newCell.SetCellValue(drValue.ParseToDouble());break;case "System.Single":case "System.Nullable`1[System.Single]":newCell.SetCellValue(drValue.ParseToDouble());break;case "System.Decimal":case "System.Nullable`1[System.Decimal]":newCell.SetCellValue(drValue.ParseToDouble());break;case "System.DBNull":newCell.SetCellValue(string.Empty);break;default:newCell.SetCellValue(string.Empty);break;}}#endregion}using (MemoryStream ms = new MemoryStream()){workbook.Write(ms);workbook.Close();ms.Flush();ms.Position = 0;return ms;}}#endregion}
}

http://www.dtcms.com/a/491417.html

相关文章:

  • PLD-150电液伺服钢管弯曲疲劳试验台
  • 个人可以做社区网站有哪些深圳市网站开发
  • 视频一页网站怎么做北京高端网站建设有限公司
  • asp.net做三个网站官网搭建
  • xr-frame微信小程序xr-ar-tracker实现video视频竖屏或横屏播放
  • JavaScript this 关键字详解
  • 镇江网站制作服务网站功能插件
  • 假电影网站做注册静态网站建设背景
  • 如何利用云服务器进行网站建设厦门网站优化服务
  • 【 广州产权交易所-注册安全分析报告-无验证方式导致安全隐患】
  • MySQL 高级分表与分库实践指南
  • SEO网站建设入驻程流旅游网站这么做
  • 网站怎么响应式布局建筑资源网站
  • 从 ROS 订阅视频话题到本地可视化与 RTMP 推流全流程实战
  • JavaScript 中的安全编码:10 个关键实践
  • 可变参数模版bug(报错原因分析:参数包未正确 “展开”)
  • Python | 班级成绩数据管理系统 分步详解
  • 笔试强训(三)
  • 房地产行业网站开发网站开发业务需求分析
  • 青岛seo精灵黑帽seo排名
  • 悟空AI CRM:合同功能,数字化合同管理的高效助手
  • 昆山建设公司网站监控视频怎么做直播网站
  • 第三章 线型神经网络
  • 【51单片机】【protues仿真】基于51单片机数字温度计数码管系统
  • 【Redis】缓存热点数据
  • 网站建设 无法打开asp青岛有没有做网站的
  • Playwright Fixture 实战:模拟数据库、API客户端与测试数据
  • wordpress分类栏目昆明排名seo公司
  • 海南蓝碳:生态财富与科技驱动的新未来
  • 济源网站建设哪家好网站开发命名规则