ASP.NET使用NPOI将数据导出Excel

1、说明

之前使用IE浏览器的ActiveX将数据导出为excel,但这个依赖于IE,且有安全隐患,因此使用第三方插件进行导出。网上找了找发现了NPOI。总的来说,挺好用。但里面也有很多坑。

2、获取开源项目,生成DLL

2.1 获取开源项目

NPOI的开源地址为:项目在GitHub的地址,从上面下载源码即可。

2.2 生成DLL

最坑的事情是源码下来后,在生成DLL过程中会出现如下的错误:
生成DLL时的错误信息

2.2.1 重新添加SS文件夹–>UserModel文件夹下的所有文件

具体操作如下:
添加现有项
UserModel文件

2.2.2 使用Nuget添加EnumsNET

添加Enums.NET基本上这样,就可以生成生成功了。成功后如下图所示
生成成功后的截图

3、使用样例

3.1 环境说明

使用了win10企业版,VS2019社区版,.NET.Framework4.7.2,ASP.NET MVC 5

3.2 特殊说明

从GitHub拉下来的最新版NPOI中,其使用了Microsoft.IO.RecyclableMemoryStream,其依赖项最低是.NET.Framework4.6.1。因此在使用NPOI时,要特别注意选择合适的版本。

3.2 通过界面的形式下载

即通过点击按钮,进行数据下载。
前端界面如下:
前端界面
下载效果如下:
在这里插入图片描述数据效果

前端代码如下:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<!--方法1-->
<!--前端可以在js文件中使用window.open('/NPOIWebTest/NPOIWeb/ExportExcel')-->
<!--方法2-->
<a href="/NPOIWebTest/NPOIWeb/ExportExcel">下载Excel</a>

Controller的代码如下:

//使用界面进行下载
public ActionResult ExportExcel()
{
   ExportClass export = new ExportClass();

   HSSFWorkbook detaildata = export.getExportData("数据导出");

   MemoryStream ms = new MemoryStream();
   
   detaildata.Write(ms);
   ms.Seek(0, SeekOrigin.Begin);

   return File(ms, "application/vnd.ms-excel", "Excel的文件名.xls");
}

其中ExportClass类源码如下:

public class ExportClass
{
    //返回展示的名称。用于excel的标题
    public List<string> getDisplayName<T>(T entity)
    {
        List<string> resultList = new List<string>();
        PropertyInfo[] pinfoArray = entity.GetType().GetProperties();
        foreach (var item in pinfoArray)
        {
            var obj = item.GetCustomAttributes(typeof(DisplayNameAttribute), true);
            if(obj!=null)
            {
                var displayName = ((DisplayNameAttribute)obj[0]).DisplayName;
                resultList.Add(displayName);
            }
        }

        return resultList;
    }


    //返回真实数据
    public List<string> getTrueValue<T>(T entity)
    {
        List<string> resultList = new List<string>();
        Type type = entity.GetType();
        PropertyInfo[] pinfoArray = type.GetProperties();

        foreach (var propertyItem in pinfoArray)
        {
            string name = propertyItem.Name;
            PropertyInfo pinfo = type.GetProperty(name);
            var theTrueValue = pinfo.GetValue(entity).ToString();

            resultList.Add(theTrueValue);
        }

        return resultList;
    }

    //返回一个Excel
    public HSSFWorkbook getExportData(string sheetname)
    {
        HSSFWorkbook book = new HSSFWorkbook();
        ISheet sheet = book.CreateSheet(sheetname);


        //获取数据
        List<ExcelDataModel> dataList = new List<ExcelDataModel>() { 
            new ExcelDataModel { TheColoumID="第(1,1)数据",TheColoumName="第(1,2)数据"},
            new ExcelDataModel { TheColoumID="第(2,1)数据",TheColoumName="第(2,2)数据"},
            new ExcelDataModel { TheColoumID="第(3,1)数据",TheColoumName="第(3,2)数据"}
        };

        //获取标题的数据
        List<string> titleList = getDisplayName<ExcelDataModel>(dataList.FirstOrDefault<ExcelDataModel>());




        ICellStyle cellStyle = book.CreateCellStyle();
        cellStyle.BorderBottom = BorderStyle.Thin;
        cellStyle.BorderLeft = BorderStyle.Thin;
        cellStyle.BorderTop = BorderStyle.Thin;
        cellStyle.BorderRight = BorderStyle.Thin;
        cellStyle.VerticalAlignment = VerticalAlignment.Center;

        //创建表头
        IRow row = sheet.CreateRow(0);
        for (int i = 0; i < titleList.Count; i++)
        {
            row.CreateCell(i).SetCellValue(titleList[i]);
        }


        //填充数据
        for (int i = 0; i < dataList.Count; i++)
        {
            IRow temprow = sheet.CreateRow(i + 1);
            var tempResult = getTrueValue(dataList[i]);
            for (int j = 0; j < titleList.Count; j++)
            {
                temprow.CreateCell(j).SetCellValue(tempResult[j]);
            }
        }

        return book;
    }

}


public class ExcelDataModel
{
    [DisplayName("第一列的名称")]
    public string TheColoumID { get; set; }

    [DisplayName("第二列")]
    public string TheColoumName { get; set; }

}
3.3 使用WebAPI将数据导出excel

API的代码如下:

[HttpGet]
public HttpResponseMessage ExportExcel()
 {
     //获取数据
     ExportClass export = new ExportClass();
     HSSFWorkbook detaildata = export.getExportData("数据导出");


     //整理返回结果
     using(MemoryStream ms = new MemoryStream())
     {
         detaildata.Write(ms);

         var response = new HttpResponseMessage(HttpStatusCode.OK)
         {
             Content = new ByteArrayContent(ms.ToArray())
         };

         response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
         response.Content.Headers.ContentDisposition =
                new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "数据excel.xlsx"
                };

         return response;

     }
 }

4、代码下载

源码下载:具体下载地址
提取码:NHZL

5、总结

总的来说,NPOI是一个不错的插件,不过建议开源项目作者把精力更多的放在永攀高峰的技术上,取的更大的成果。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值