您的位置:首页 > 编程语言 > ASP

Asp.Net MVC5 使用NPIO导出Excel数据文件方法总结

2018-03-06 13:36 656 查看
 在系统开发过程中导出Excel功能是经常遇到的需求,我们知道在asp.net webform中很简单,采用Response.Write一个文件就可以了。但是在Asp.Net mvc有的人就不太清楚了,因为Asp.Net MVC和asp.net webform响应还是有一些区别的。今天我就总结一下Asp.Net MVC5 使用导出Excel数据文件方法。

一、项目准备

下载:NPOI 2.1.1采用VS2013创建一个Asp.Net MVC5的项目。有以下文件:

接下来为项目添加引用,最终的结果如下图:

视图部分Excel.cshtml:@{
ViewBag.Title = "Excel";
}

<h2>Excel</h2>
<p><a class="btn btn-default" href="@Url.Action("ExportToExcel")">导出Excel</a></p>

二、采通过表格的形式输出

public ActionResult ExportToExcel()
{
var sbHtml = new StringBuilder();
sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");
sbHtml.Append("<tr>");
var lstTitle = new List<string> { "编号", "姓名", "年龄", "创建时间" };
foreach (var item in lstTitle)
{
sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
}
sbHtml.Append("</tr>");

for (int i = 0; i < 100; i++)
{
sbHtml.Append("<tr>");
sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", i);
sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>屌丝{0}号</td>", i);
sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", new Random().Next(20, 30) + i);
sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", DateTime.Now);
sbHtml.Append("</tr>");
}
sbHtml.Append("</table>");

//第一种:使用FileContentResult
     byte[] fileContents = Encoding.UTF8.GetBytes(sbHtml.ToString());
return File(fileContents, "application/ms-excel", "fileContents.xls");

//第二种:使用FileStreamResult
//var fileStream = new MemoryStream(fileContents);
//return File(fileStream, "application/ms-excel", "fileStream.xls");

//第三种:使用FilePathResult
//服务器上首先必须要有这个Excel文件,然会通过Server.MapPath获取路径返回.
//var fileName = Server.MapPath("~/Files/fileName.xls");
//return File(fileName, "application/ms-excel", "fileName.xls");
}

三、采用NPIO方式

目一篇文章开源类库组件NPIO-.NET下的Excel利器--简介介绍了一下NPIO组件,下面我就看看NPIO在ASP.NET MVC5中导出Excel功能。public ActionResult ExportToExcel2()
{
NPOI.SS.UserModel.IWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();
NPOI.SS.UserModel.ICell cell;
NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("StressTest");
int i = 0;
int rowLimit = 100;
DateTime originalTime = DateTime.Now;
for (i = 0; i < rowLimit; i++)
{
cell = sheet.CreateRow(i).CreateCell(0);
cell.SetCellValue("值"+i.ToString());
}

using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
var buffer = ms.GetBuffer();
ms.Close();
return File(buffer, "application/ms-excel","test.xlsx");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: