1. 程式人生 > >使用NPOI 做Excel導出

使用NPOI 做Excel導出

文件 info temp user col count() mode order 寫入

1.先去官網:http://npoi.codeplex.com/下載需要引入dll 然後在網站中添加引用。
2.Asp.Net mvc導出方法
///
<summary> /// 導出Excel /// </summary> /// <returns></returns> public FileResult Excel() { var alist = WishWallServices.QueryWhere(c => c.status == 1).OrderByDescending(c=>c.WishThumbup.Where(q=>q.status==1
).Count()).ToList(); //創建Excel文件的對象 NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); //添加一個sheet NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("心願墻"); //給sheet添加第一行的頭部標題 NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0
); row1.CreateCell(0).SetCellValue("微信號"); row1.CreateCell(1).SetCellValue("姓名"); row1.CreateCell(2).SetCellValue("心願標題"); row1.CreateCell(3).SetCellValue("心願內容"); row1.CreateCell(4).SetCellValue("點贊數"); row1.CreateCell(5).SetCellValue("
聯系方式"); row1.CreateCell(6).SetCellValue("聯系地址"); //....N行 //將數據逐步寫入sheet1各個行 for (int i = 0; i < alist.Count; i++) { NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1); rowtemp.CreateCell(0).SetCellValue(alist[i].WeiXinInfo.WeiXinName); rowtemp.CreateCell(1).SetCellValue(alist[i].name); rowtemp.CreateCell(2).SetCellValue(alist[i].title); rowtemp.CreateCell(3).SetCellValue(alist[i].content); rowtemp.CreateCell(4).SetCellValue(alist[i].WishThumbup.Where(q=>q.status==1).Count()); rowtemp.CreateCell(5).SetCellValue(alist[i].phone); //....N行 } System.IO.MemoryStream ms = new System.IO.MemoryStream(); book.Write(ms); ms.Seek(0, SeekOrigin.Begin); return File(ms, "application/vnd.ms-excel", "心願墻.xls"); }

使用NPOI 做Excel導出