c#基础学习(0629)之导出Excel方法

时间:2021-11-21 21:35:58
给予NPOI插件的方法,所以首先要下载NPOI插件:vs项目中点击“项目”==》“管理NoGet程序包”==》搜索“NPOI”然后下载==》using引入

Controller代码:
public class ExcelController : Controller
{
/// <summary>
/// 利用NPOI插件
/// </summary>
/// <returns></returns>
public FileResult ExportStu2()
{
DataTable dt = (DataTable)Session["datatable"];//获取需要导出的datatable数据
//创建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();
//row1.RowStyle.FillBackgroundColor = "";
for (int i = ; i < dt.Columns.Count; i++)
{
row1.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
}
//将数据逐步写入sheet1各个行
for (int i = ; i < dt.Rows.Count; i++)
{
NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
rowtemp.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString().Trim());
}
}
string strdate = DateTime.Now.ToString("yyyyMMddhhmmss");//获取当前时间
// 写入到客户端
System.IO.MemoryStream ms = new System.IO.MemoryStream();
book.Write(ms);
ms.Seek(, SeekOrigin.Begin);
return File(ms, "application/vnd.ms-excel", strdate + "Excel.xls");
}
}

html代码:

@Html.ActionLink("导出Excel", "ExportStu2","Excel")