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

     [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. HBase实战 | 知乎实时数仓架构演进

    https://mp.weixin.qq.com/s/hx-q13QteNvtXRpNsE5Y0A 作者 | 知乎数据工程团队编辑 | VincentAI 前线导读:“数据智能” (Data Inte ...

  2. EF-CodeFirst-数据库初始化

    数据库初始化 之前看到Code-First会自动根据域模型创建数据库,下图展示了一个数据库初始化工作流程,该工作流程基于从DbContext派生的上下文类的基础构造函数中传递的参数 如上图所示,上下文 ...

  3. TensorFlow安装之后导入报错:libcudnn.so.6:cannot open sharedobject file: No such file or directory

    转载自:http://blog.csdn.net/silent56_th/article/details/77587792 系统环境:Ubuntu16.04 + GTX1060 目的:配置一下pyth ...

  4. 二、Spring Boot 配置文件

    1.配置文件 Spring Boot使用一个全局的配置文件,配置文件名是固定的 application.properties applicatioin.yml 配置文件的作用:修改Spring Boo ...

  5. python基础教程 变量/输入输出/if判断

    python的运用越来越多.大数据经常被人谈及,数据从何而来?通过各个平台.app.网站数据的收集,分析,过滤,生成报告,这些都可以用python来处理,并且有很多成熟的库可以直接用了.那还不赶紧深入 ...

  6. 报错解决——DateTimeField *** received a naive datetime (***) while time zone support is active

    这是一个跟时区有关的问题,报错中说到datetime字段得到一个naive datetime,而不是支持time zone的active datetime由于Django的设置中米哦人USE_TZ设置 ...

  7. winform里直接使用WCF,不需要单独的WCF项目

    https://www.cnblogs.com/fengwenit/p/4249446.html 依照此法建立即可, 但是vs生成的配置有误,正确配置如下 <?xml version=" ...

  8. error: Microsoft Visual C++ 14.0 is required(line_profiler模块安装失败的解决办法)

    一.我的安装环境: 1.系统:win10,64位 2.python版本:python3.6.4 二.遇到的问题: 1.cmd黑屏终端下输入命令:pip install line_profiler(安装 ...

  9. abap 通过importing 和 exporting 调用其它函数

    1:其它函数的(输入或输出)参数名都在=号左边.

  10. strncat、strcat

    strncat函数 2007年03月15日 20:32:00 阅读数:13676 函数原型:extern char *strncat(char *dest,char *src,int n) 参数说明: ...