ASP.NET MVC使用EPPlus,导出数据到Excel中
好久没写博客了,今天特地来更新一下,今天我们要学习的是如何导出数据到excel文件中,这里我使用的是免费开源的epplus组件。
源代码下载:https://github.com/caofangsheng93/excelexportinmvc
介绍
这篇文章,介绍的是怎样导出数据到excel文件中,大多数的后端程序都有报表功能:把显示在grid中的数据导出到excel文件中,这篇文章中使用的是epplus组件。
epplus是一个基于ooxml【open extended markup language 】格式的,操作excel表格的类库。ooxml是由微软开发的。默认支持微软的office。
开源网站:
正文
上面是我们的项目。
首先我们需要引入:epplus。
我这里已经引入了。
当我们在程序中使用orm的时候,我们通常将数据保存在集合中。集合中的数据不能直接导出到excel文件中。这也就是我们为啥,需要先将list转datatable的原因。
图1 :导出excel的步骤
为了完成这篇文章:我们需要四个步骤:
1.数据:这里我使用静态数据,来确保这篇文章尽可能通俗易懂。
2.集合:静态数据保存在集合中
3.datatable:转化泛型集合的数据,保存到datatable中
4.导出文件:datatable导出为excel
首先,我们创建一个类:
public class student { public int id { get; set; } public string name { get; set; } public string sex { get; set; } public int age { get; set; } public string email { get; set; } } student
然后创建一个静态数据类:
public class staticdataofstudent { public static list<student> liststudent { get { return new list<student>() { new student(){id=1,name="曹操",sex="男",email="caocao@163.com",age=24}, new student(){id=2,name="李易峰",sex="女",email="lilingjie@sina.com.cn",age=24}, new student(){id=3,name="张三丰",sex="男",email="zhangsanfeng@qq.com",age=224}, new student(){id=4,name="孙权",sex="男",email="sunquan@163.com",age=1224}, }; } } } staticdataofstudent
然后就是我们的导出excel帮助类了:
/// <summary> /// excel导出帮助类 /// </summary> public class excelexporthelper { public static string excelcontenttype { get { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } } /// <summary> /// list转datatable /// </summary> /// <typeparam name="t"></typeparam> /// <param name="data"></param> /// <returns></returns> public static datatable listtodatatable<t>(list<t> data) { propertydescriptorcollection properties = typedescriptor.getproperties(typeof(t)); datatable datatable = new datatable(); for (int i = 0; i < properties.count; i++) { propertydescriptor property = properties[i]; datatable.columns.add(property.name, nullable.getunderlyingtype(property.propertytype) ?? property.propertytype); } object[] values = new object[properties.count]; foreach (t item in data) { for (int i = 0; i < values.length; i++) { values[i] = properties[i].getvalue(item); } datatable.rows.add(values); } return datatable; } /// <summary> /// 导出excel /// </summary> /// <param name="datatable">数据源</param> /// <param name="heading">工作簿worksheet</param> /// <param name="showsrno">//是否显示行编号</param> /// <param name="columnstotake">要导出的列</param> /// <returns></returns> public static byte[] exportexcel(datatable datatable, string heading = "", bool showsrno = false, params string[] columnstotake) { byte[] result = null; using(excelpackage package=new excelpackage()) { excelworksheet worksheet = package.workbook.worksheets.add(string.format("{0}data", heading)); int startrowfrom = string.isnullorempty(heading) ? 1 : 3; //开始的行 //是否显示行编号 if (showsrno) { datacolumn datacolumn = datatable.columns.add("#", typeof(int)); datacolumn.setordinal(0); int index = 1; foreach (datarow item in datatable.rows) { item[0] = index; index++; } } //add content into the excel file worksheet.cells["a" + startrowfrom].loadfromdatatable(datatable, true); // autofit width of cells with small content int columnindex = 1; foreach (datacolumn item in datatable.columns) { excelrange columncells = worksheet.cells[worksheet.dimension.start.row, columnindex, worksheet.dimension.end.row, columnindex]; int maxlength = columncells.max(cell => cell.value.tostring().count()); if (maxlength < 150) { worksheet.column(columnindex).autofit(); } columnindex++; } // format header - bold, yellow on black using (excelrange r = worksheet.cells[startrowfrom, 1, startrowfrom, datatable.columns.count]) { r.style.font.color.setcolor(system.drawing.color.white); r.style.font.bold = true; r.style.fill.patterntype = officeopenxml.style.excelfillstyle.solid; r.style.fill.backgroundcolor.setcolor(system.drawing.colortranslator.fromhtml("#1fb5ad")); } // format cells - add borders using (excelrange r = worksheet.cells[startrowfrom + 1, 1, startrowfrom + datatable.rows.count, datatable.columns.count]) { r.style.border.top.style = excelborderstyle.thin; r.style.border.bottom.style = excelborderstyle.thin; r.style.border.left.style = excelborderstyle.thin; r.style.border.right.style = excelborderstyle.thin; r.style.border.top.color.setcolor(system.drawing.color.black); r.style.border.bottom.color.setcolor(system.drawing.color.black); r.style.border.left.color.setcolor(system.drawing.color.black); r.style.border.right.color.setcolor(system.drawing.color.black); } // removed ignored columns for (int i = datatable.columns.count - 1; i >= 0; i--) { if (i == 0 && showsrno) { continue; } if (!columnstotake.contains(datatable.columns[i].columnname)) { worksheet.deletecolumn(i + 1); } } if (!string.isnullorempty(heading)) { worksheet.cells["a1"].value = heading; worksheet.cells["a1"].style.font.size = 20; worksheet.insertcolumn(1, 1); worksheet.insertrow(1, 1); worksheet.column(1).width = 5; } result = package.getasbytearray(); } return result; } /// <summary> /// 导出excel /// </summary> /// <typeparam name="t"></typeparam> /// <param name="data"></param> /// <param name="heading"></param> /// <param name="isshowslno"></param> /// <param name="columnstotake"></param> /// <returns></returns> public static byte[] exportexcel<t>(list<t> data, string heading = "", bool isshowslno = false, params string[] columnstotake) { return exportexcel(listtodatatable<t>(data), heading, isshowslno, columnstotake); } }
到此为止,后端服务器的代码,基本搞完,现在开始设计我们的前端代码:
我们创建一个viewmodel,用来显示数据:
public class studentviewmodel { public list<student> liststudent { get { return staticdataofstudent.liststudent; } } }
然后创建一个控制器:
public class homecontroller : controller { // get: home public actionresult index() { studentviewmodel model = new studentviewmodel(); return view(model); } public filecontentresult exporttoexcel() { list<student> lststudent = staticdataofstudent.liststudent; string[] columns = { "id", "name","age"}; byte[] filecontent = excelexporthelper.exportexcel(lststudent,"", false, columns); return file(filecontent, excelexporthelper.excelcontenttype, "mystudent.xlsx"); } }
我们的视图代码:
@model exporttoexcel.models.studentviewmodel @{ viewbag.title = "excel文件导出"; } <div class="panel"> <div class="panel-heading"> <a href="@url.action("exporttoexcel")" class="btn btn-primary">export</a> </div> <div class="panel-body"> <table class="table table-striped table-bordered"> <thead> <tr> <th>id</th> <th>name</th> <th>sex</th> <th>age</th> <th>email</th> </tr> </thead> <tbody> @foreach (var item in model.liststudent) { <tr> <td>@item.id</td> <td>@item.name</td> <td>@item.sex</td> <td>@item.age</td> <td>@item.email</td> </tr> } </tbody> </table> </div> </div>
效果图:
点击export之后,就导出了excel文件到浏览器中:打开之后。
总结:这个导出帮助类,可以定制导出那些列。
string[] columns = { "id", "name","age"}; byte[] filecontent = excelexporthelper.exportexcel(lststudent,"", false, columns); return file(filecontent, excelexporthelper.excelcontenttype, "mystudent.xlsx");
这里我只是导出这三列。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!