数据导出至excle


ASP.NET MVC导出Excel

首先下载  NPOI.dll 引用到项目中

建议下载地址:http://download.csdn.net/detail/pukuimin1226/5851747

前台代码:

<a href='/Admin/NurseUser/Excel' target='_blank'>导出Excel</a>

后台代码:


public FileResult Excel() { //获取list数据 var list = bll.NurseUserListExcel("", "ID asc"); //创建Excel文件的对象 NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); //添加一个sheet NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1"); //给sheet1添加第一行的头部标题 NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0); row1.CreateCell(0).SetCellValue("ID"); row1.CreateCell(1).SetCellValue("用户姓名"); row1.CreateCell(2).SetCellValue("电话"); row1.CreateCell(3).SetCellValue("注册时间"); row1.CreateCell(4).SetCellValue("邀请人ID"); row1.CreateCell(5).SetCellValue("邀请人名称"); row1.CreateCell(6).SetCellValue("邀请人电话"); row1.CreateCell(7).SetCellValue("总积分"); row1.CreateCell(8).SetCellValue("已使用积分"); row1.CreateCell(9).SetCellValue("可用积分"); //将数据逐步写入sheet1各个行 for (int i = 0; i < list.Count; i++) { NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1); rowtemp.CreateCell(0).SetCellValue(list[i].ID); rowtemp.CreateCell(1).SetCellValue(list[i].Name); rowtemp.CreateCell(2).SetCellValue(list[i].Phone); rowtemp.CreateCell(3).SetCellValue(list[i].CreateTime.Value.ToString()); rowtemp.CreateCell(4).SetCellValue(list[i].InviterID.Value); rowtemp.CreateCell(5).SetCellValue(list[i].iName); rowtemp.CreateCell(6).SetCellValue(list[i].iPhone); rowtemp.CreateCell(7).SetCellValue(list[i].IntegralSum); rowtemp.CreateCell(8).SetCellValue(list[i].IntegralSy); rowtemp.CreateCell(9).SetCellValue(list[i].IntegralKy); } // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); book.Write(ms); ms.Seek(0, SeekOrigin.Begin); return File(ms, "application/vnd.ms-excel", "用户信息.xls"); }

2.动态生成Excle

public MemoryStream GetExecelByDT(DataTable dt) //返回的是文件流
{
HSSFWorkbook book = new HSSFWorkbook();
ISheet sheet = book.CreateSheet("2019项目列表情况表");
IRow ColumnsName = sheet.CreateRow(0);
//获取列名并且向Excel中填充列
for (int i = 0; i < dt.Columns.Count; i++)
{
ColumnsName.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
}
//向Excel中填充数据
//循环每一行
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow DataRow = sheet.CreateRow(i + 1);
//循环每一列
for (int j = 0; j < dt.Columns.Count; j++)
{
DataRow.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
}
}
MemoryStream ms = new MemoryStream();
book.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
return ms;
}

 

public void main()

{

//保存文件路径
string fullPath = System.IO.Path.Combine("文件路径" + 文件名.xlsx);

//根据数据生成文件流
MemoryStream exportData = new ExcelRanderBLL().GetExecelByDT(dt);

FileStream file = new FileStream(fullPath, FileMode.Create, FileAccess.Write);
//将文件流写入指定的文件里
exportData.WriteTo(file);
file.Close();

}

 

posted @ 2019-03-21 11:35  Sky丨芒果  阅读(263)  评论(0编辑  收藏  举报