net npoi将List<实体>导出excel的最简单方法
一、最屌丝的方法。只是临时导数据用的。方便。最基本的方法,
[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的最简单方法的更多相关文章
- 使用NPOI或EPPlus来导出Excel文件实例,可在Excel文件加密
使用NPOI.dll组件来导出Excel文件,并设置样式,Nuget引用即可. packages\NPOI.2.1.3.1\lib\net20\NPOI.dll #region Excel prote ...
- .NET导出Excel的四种方法及评测
.NET导出Excel的四种方法及评测 导出Excel是.NET的常见需求,开源社区.市场上,都提供了不少各式各样的Excel操作相关包.本文,我将使用NPOI.EPPlus.OpenXML.Aspo ...
- [转帖].NET导出Excel的四种方法及评测
.NET导出Excel的四种方法及评测 https://www.cnblogs.com/sdflysha/p/20190824-dotnet-excel-compare.html 导出Excel是.N ...
- DataGird导出EXCEL的几个方法
DataGird导出EXCEL的几个方法(WebControl) using System;using System.Data;using System.Text;using System.Web;u ...
- 传参导出Excel表乱码问题解决方法
业务场景 先描述一下业务场景,要实现的功能是通过搜索框填写参数,然后点击按钮搜索数据,将搜索框的查询参数获取,附加在链接后面,调导Excel表接口,然后实现导出Excel功能.其实做导Excel表功能 ...
- 使用Python处理Excel表格的简单方法
使用Python处理Excel表格的简单方法 这篇文章主要介绍了使用Python处理Excel表格的简单方法,本文给大家介绍的非常详细,需要的朋友可以参考下 Excel 中的每一个单元,都会有这些属性 ...
- asp.net mvc4使用NPOI 数据处理之快速导出Excel文档
一.背景 在之前做的小项目里有一需求是:要求将一活动录入的数据进行统计,并以excel表格形式导出来,并且对表格格式要求并不高. 二.问题分析 鉴于用户只要求最终将数据库中的数据导出excel,对于格 ...
- .NET使用NPOI组件将数据导出Excel
.NPOI官方网站:http://npoi.codeplex.com/ 可以到此网站上去下载最新的NPOI组件版本 2.NPOI在线学习教程(中文版): http://www.cnblogs.com/ ...
- POI导出Excel文档通用工具方法
import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; imp ...
随机推荐
- dbclient python ---influxdb -install -relay--http write--read.[create db]
1s=1000ms 1ms=1000 microseconds 1microsecond=1000 nanoseconds+01:00 from influxdb import InfluxDBCli ...
- [daily][editer] 二进制编辑工具 hyx
用了众多之后,终于发现了一个好用的二进制编辑工具: hyx https://yx7.cc/code/ https://en.wikipedia.org/wiki/Comparison_of_hex_e ...
- Flink – metrics V1.2
WebRuntimeMonitor .GET("/jobs/:jobid/vertices/:vertexid/metrics", handler(new JobVertexM ...
- 转:Scanner中nextLine()方法和next()方法的区别
原文地址:https://blog.csdn.net/hello_word2/article/details/54895106 总结:next() 读取第一个 空白符之前(不包括空白符)的内容,nex ...
- HTML5上传文件显示进度
下面我们使用Html 5的新特性file api实现上传文件,并显示上传文件进度百分比.意图是这样的,当选择文件时,显示当前文件信息.这里我们是结合Asp.net MVC做为服务端,您也可以是其它的服 ...
- input的placeholder在ie9下不兼容的结局办法。
/* IE9placeholder支持 */ if(!placeholderSupport()){ // 判断浏览器是否支持 placeholder ...
- P1879 [USACO06NOV]玉米田Corn Fields 状压dp/插头dp
正解:状压dp/插头dp 解题报告: 链接! ……我真的太菜了……我以为一个小时前要搞完的题目调错误调了一个小时……90分到100我差不多搞了一个小时…… 然后这题还是做过的……就很气,觉得确实是要搞 ...
- VS2013 opencv配置
有三个地方需要配置,在配置之前首先要将platform配置好,下面的例子是x64 Release的“ 然后需要将include.lib的路径配置好 然后将dll拷贝至编译生成的Release文件夹中即 ...
- mysql from dual插入实现不插入重复记录
在mysql中插入一或者多条记录的时候,要求某个字段的值唯一,但是该字段没有添加唯一性索引,可用from dual解决. select * from (select '2015080109' a,2 ...
- centos7 管理开机启动:systemd
一.CentOS7 systemd 介绍 在 CentOS7 中,使用 systemd 来管理其他服务是否开机启动,systemctl 是 systemd 服务的命令行工具 [root@mysql ~ ...