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

给予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(0);
            //row1.RowStyle.FillBackgroundColor = "";
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                row1.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
            }
            //将数据逐步写入sheet1各个行
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                for (int j = 0; 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(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", strdate + "Excel.xls");
        }
    }

html代码:

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

 

posted @ 2018-06-29 14:30  超哥20  阅读(240)  评论(0编辑  收藏  举报