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

     [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. c#加"\n\r"不换行,变成字符串

    质检模块,本想将每个错误分行, 比如:lyrerrormess += lyrname + "图层" + "缺少" + xmlFieldName + " ...

  2. ionic使用cordova插件中的Screenshot截图分享功能

    需要实现操作,考试完成后需要将成绩生成一张图片,分享出去, import { Screenshot } from '@ionic-native/screenshot'; constructor(pri ...

  3. [development][c++] C++构造函数调用构造函数

    构造函数调用构造函数是会问题的. 外层函数返回的内存, 与被调用的构造函数返回的内存并不是一个内存. 错误示例代码如下: msg_log(const char *name, const char* t ...

  4. mongodb 数组查询

    转发自:https://blog.csdn.net/leshami/article/details/55049891 一.演示环境及数据> db.version() 3.2.11 > db ...

  5. 这就是使用ReportBuilder最简单的例子

    用这组控件最简单的例子:在窗体上放上组件名为ppBDEPipeline1,ppReport1,ppDesigner1,ppViewer1,DataSource1的控件,设置ppreport1的data ...

  6. java jdk安装配置

    1. 配置java_home 2. path添加: %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin; 3. 添加CLASSPATH路径: .;%Java_Home%\bin;% ...

  7. ATL Thunk机制深入分析

    如果你有SDK的编程经验,就一定应该知道在创建窗口时需要指定窗口类,窗口类中的一种重要的参数就是窗口过程.任何窗口接收到的消息,都是由该窗口过程来处理. 在面向对象编程中,如果还需要开发人员来使用原始 ...

  8. 3 jmeter的两种录制方法

    录制1-badboy(推荐) badboy是一款自动化测试工具,它可以完成简单的功能测试和性能测试.其实它是一款独立的测试工具,只不过它录制东西导出的格式适用于jmeter,所以我们经常把jmeter ...

  9. 并发编程---开启进程方式---查看进程pid

    1.开启进程的两种方式 方式一: from multiprocessing import Process import time def task(name): print('%s is runnin ...

  10. XML 文档(1, 2)中有错误:不应有 <xml xmlns=''>

    症状 用XmlSerializer进行xml反序列化的时候,程序报错: 不应有 <xml xmlns=''>. 说明: 执行当前 Web 请求期间,出现未经处理的异常.请检查堆栈跟踪信息, ...