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 ...
随机推荐
- CHARACTER SET
mysql> show tables; +-----------------+ | Tables_in_w0811 | +-----------------+ | t | | w_engine ...
- 【转】escape()、encodeURI()、encodeURIComponent()区别详解
escape().encodeURI().encodeURIComponent()区别详解 原文链接:http://www.cnblogs.com/tylerdonet/p/3483836.html ...
- Http-server 的使用
Http-server 是一款基于node.js的web前端开发服务,可以很好的承担前后端解耦后,前端服务的搭建. 1,首先安装node node下载地址:https://nodejs.org/zh- ...
- python之文件操作示例
方法一: with open("e:\\gloryroad.txt","a+",encoding="utf-8") as file: fil ...
- Vue中父子组件执行的先后顺序
Vera Vue中父子组件执行的先后顺序探讨(转载) 前几天,朋友向我提出了一个关于Vue中父子组件执行的先后顺序问题,相信很多朋友在学习的过程中也会遇到这个问题,所以我就在此提出我自己的一些小看 ...
- canvas将图片转成base64格式 以及 验证图片是否透明
logoImgUpload:function(file) { let self = this; self.formatUpload(file); let reader = new FileReader ...
- java 大数据运算 BigInteger BigDecimal
package cn.sasa.demo5; import java.math.BigDecimal; import java.math.BigInteger; public class BigDat ...
- 第 9 章 DOM 的增删改查
DOM 的增删改查 本文不会详细讲解,只是简单提及知识要点,详细可以参考<dom高级编程>. 1. document.write document.write('<h1>创建节 ...
- es分页搜索
1.es分页语法GET /_search?from=起始数&size=页面显示条数例如:GET /test_index/test_type/_search?from=0&size=3 ...
- RN正、反向传值,组件输出
很简单的一个小Demo,绿色的是输出的一个组件,目标把’爱好‘从父组件传给子组件,然后把’name‘从子组件传给父组件 父组件给子组件传值可以使用props,子组件传值给父组件可以使用事件,这里不多说 ...