一、最屌丝的方法。只是临时导数据用的。方便。最基本的方法,

     [HttpGet]
[Route("ExportEnterprise")]
public BaseResponse ExportEnterprise()
{
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("onesheet");
IRow row0 = sheet.CreateRow();
row0.CreateCell().SetCellValue("顺序号");
row0.CreateCell().SetCellValue("企业名");
row0.CreateCell().SetCellValue("行业门类");
row0.CreateCell().SetCellValue("行业大类");
row0.CreateCell().SetCellValue("经营属地");
row0.CreateCell().SetCellValue("法人");
row0.CreateCell().SetCellValue("法人手机");
row0.CreateCell().SetCellValue("法人固话"); var enterprises = _enterpriseService.GetEnterprisesOfTest().ToList();
var lineNo = ;
foreach (var enterprise in enterprises)
{
IRow row = sheet.CreateRow(lineNo);
row.CreateCell().SetCellValue(lineNo);
row.CreateCell().SetCellValue(enterprise.EnterpriseName);
var doorDescr = _industryCategoryService.GetDescriptionBy(enterprise.IndustryCategoryCode);
row.CreateCell().SetCellValue(doorDescr);
var industryGeneraDescr = _industryCategoryService.GetDescriptionBy(enterprise.IndustryGeneraCode);
row.CreateCell().SetCellValue(industryGeneraDescr);
row.CreateCell().SetCellValue(_administrativeDivisionService.GetDescriptionBy(enterprise.BusinessAddressDivisonCode));
row.CreateCell().SetCellValue(enterprise.LegalPersonName);
row.CreateCell().SetCellValue(enterprise.LegalPersonPhone);
row.CreateCell().SetCellValue(enterprise.LegalPersonFixedPhone);
lineNo++;
} //创建流对象并设置存储Excel文件的路径
using (FileStream url = new FileStream(HttpContext.Current.Server.MapPath("/App_Data/test.xls"), FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
//导出Excel文件
workbook.Write(url);
};
return Success(new BaseResponse());
}

二、高大上的通用方法

在baseController里写个通用方法,利用反射原理,获取对象的每一个属性的DisplayName作表头

/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileBaseName">不带后缀</param>
/// <param name="datas"></param>
/// <returns></returns>
public ActionResult ExportToExcel<T>(string fileBaseName, List<T> datas) where T: ExcelModel
{
MemoryStream ms = new MemoryStream();
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("导出数据");
IRow headerRow = sheet.CreateRow(); int rowIndex = , piIndex = ;
Type type = typeof(T);
PropertyInfo[] pis = type.GetProperties();
int pisLen = pis.Length;
PropertyInfo pi = null;
string displayName = string.Empty;
while (piIndex < pisLen)
{
pi = pis[piIndex];
var pName = pi.GetCustomAttribute<DisplayNameAttribute>();
displayName = pName?.DisplayName??string.Empty;
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 = ;
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);
ms.Seek(, SeekOrigin.Begin);
return File(ms, "application/vnd.ms-excel", $"{fileBaseName}.xls");
}

对象值 需要加displayName注解

  public class ActivityGradeExcelModel: ExcelModel
{
[DisplayName("月份")]
[DisplayFormat(DataFormatString = "yyyy-MM")]
public DateTime ConductDate { get; set; }
[DisplayName("活动")]
public string ActivityName { get; set; }
[DisplayName("姓名")]
public string StudentName { get; set; }
[DisplayName("分数")]
public decimal Score { get; set; }
[DisplayName("班级")]
public string SchoolClassName { get; set; }
[DisplayName("学号")]
public string StudyNo { get; set; }
[DisplayName("专业")]
public string CollegeMajor { get; set; }
[DisplayName("学期")]
public int ConductYear { get; set; } }

Action中代码

  var gradeModels = query.OrderByDescending(m => m.ConductDate).ThenBy(m => m.ActivityName)
.ThenBy(m => m.SchoolClassName)
.Select(m => new ActivityGradeExcelModel()
{
ConductDate = m.ConductDate,
ActivityName = m.ActivityName,
StudentName = m.StudentName,
Score = m.Score,
SchoolClassName = m.SchoolClassName,
StudyNo = m.StudyNo,
CollegeMajor = m.CollegeMajor,
ConductYear = m.ConductYear
}).ToList();
var fileBaseName = $"活动成绩表{DateTime.Now.ToString("yyyyMMdd")}";
return ExportToExcel(fileBaseName, gradeModels);

net npoi将List<实体>导出excel的最简单方法的更多相关文章

  1. 使用NPOI或EPPlus来导出Excel文件实例,可在Excel文件加密

    使用NPOI.dll组件来导出Excel文件,并设置样式,Nuget引用即可. packages\NPOI.2.1.3.1\lib\net20\NPOI.dll #region Excel prote ...

  2. .NET导出Excel的四种方法及评测

    .NET导出Excel的四种方法及评测 导出Excel是.NET的常见需求,开源社区.市场上,都提供了不少各式各样的Excel操作相关包.本文,我将使用NPOI.EPPlus.OpenXML.Aspo ...

  3. [转帖].NET导出Excel的四种方法及评测

    .NET导出Excel的四种方法及评测 https://www.cnblogs.com/sdflysha/p/20190824-dotnet-excel-compare.html 导出Excel是.N ...

  4. DataGird导出EXCEL的几个方法

    DataGird导出EXCEL的几个方法(WebControl) using System;using System.Data;using System.Text;using System.Web;u ...

  5. 传参导出Excel表乱码问题解决方法

    业务场景 先描述一下业务场景,要实现的功能是通过搜索框填写参数,然后点击按钮搜索数据,将搜索框的查询参数获取,附加在链接后面,调导Excel表接口,然后实现导出Excel功能.其实做导Excel表功能 ...

  6. 使用Python处理Excel表格的简单方法

    使用Python处理Excel表格的简单方法 这篇文章主要介绍了使用Python处理Excel表格的简单方法,本文给大家介绍的非常详细,需要的朋友可以参考下 Excel 中的每一个单元,都会有这些属性 ...

  7. asp.net mvc4使用NPOI 数据处理之快速导出Excel文档

    一.背景 在之前做的小项目里有一需求是:要求将一活动录入的数据进行统计,并以excel表格形式导出来,并且对表格格式要求并不高. 二.问题分析 鉴于用户只要求最终将数据库中的数据导出excel,对于格 ...

  8. .NET使用NPOI组件将数据导出Excel

    .NPOI官方网站:http://npoi.codeplex.com/ 可以到此网站上去下载最新的NPOI组件版本 2.NPOI在线学习教程(中文版): http://www.cnblogs.com/ ...

  9. POI导出Excel文档通用工具方法

    import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; imp ...

随机推荐

  1. PHP之后期静态绑定

    PHP后期静态绑定的(late static bindings) 理解PHP延迟静态绑定 static::中的static其实是运行时所在类的别名,并不是定义类时所在的那个类名.这个东西可以实现在父类 ...

  2. 《mongoDB》概念-数据类型

    一:概念 - mongoDB 是一个面向文档的数据库,而不是关系型数据库. - 摘自<mongoDB 权威指南 第2版>第3页 二:数据类型 - null - 用于表示空值或者不存在的字段 ...

  3. 《Mysql 日志结构》

    推荐一首歌 - <往后余生>王贰浪 发现自己每天就听这么几首歌 一:慢查询日志 - SQL 完成查询并完成对于锁资源的释放之后,msqld 会将符合条件的SQL写入慢日志.因此慢日志可能和 ...

  4. spring相关的maven依赖

    <properties> <springframework.version>5.0.4.RELEASE</springframework.version> < ...

  5. Java如何对List集合的操作方法(一)

    目录: list中添加,获取,删除元素: list中是否包含某个元素: list中根据索引将元素数值改变(替换): list中查看(判断)元素的索引: 根据元素索引位置进行的判断: 利用list中索引 ...

  6. Nor Flash 驱动框架

    框架入口源文件: lcd.c (可根据入口源文件,再按着框架到内核走一遍) 内核版本:linux_2.6.22.6      硬件平台:JZ2440 以下是驱动框架: 以下是驱动代码 s3c_nor_ ...

  7. membership DB生成 & dll 强命名 & 证书生成

    UPD(Membership)数据库安装1.使用 Aspnet_regsql.exe 安装数据库 在 C:\WINDOWS\Microsoft.NET\Framework\\aspnet_regsql ...

  8. SQL Server2008及以上 表分区操作详解

    SQL Server 表分区之水平表分区  转自:https://www.cnblogs.com/Brambling/p/6766482.html 什么是表分区? 表分区分为水平表分区和垂直表分区,水 ...

  9. Dockerfile语法解析

    Dockfile介绍 从上到下依次执行 每次执行一条指令就创建一个镜像层 第一条指令必须是FROM    表示需要构建的镜像是由哪个镜像为基础镜像   后续的指令运行于此基准镜像所提供的运行环境 可以 ...

  10. ORACLE入门之Linux基础篇

    VIM0 这是数字『0 』:移动到这一行的最前面字符处$    移动到这一行的最后面字符处G    移动到这个档案的最后一行nG   n 为数字.移动到这个档案的第n 行.例如20G 则会移动到这个档 ...