1 using NPOI.HSSF.UserModel; 2 using NPOI.SS.UserModel; 3 using System; 4 using System.Collections.Generic; 5 using System.Linq; 6 using System.Web; 7 using System.Web.Mvc; 8 using System.IO; 9 using System.Data.SqlClient; 10 using System.Data; 11 12 namespace ExportDataFromDatabaseToExcel.Controllers 13 { 14 public class ExportController : Controller 15 { 16 //視圖頁 17 public ActionResult DiplayFirstPage() 18 { 19 return View(); 20 } 21 22 /// NPOI下載電子表格.xls版本 23 /// </summary> 24 /// <returns></returns> 25 public ActionResult ExportToExcel02() 26 { 27 //實例化數據庫鏈接對象,構造函數傳入數據庫連接地址 28 using (SqlConnection connection = new SqlConnection("Data Source=KAKA-20200829GR;Initial Catalog=DbForNPOI;Integrated Security=True")) 29 { 30 //實例化數據庫適配器對象,根據sql進行匹配 31 using (SqlDataAdapter adapter = new SqlDataAdapter("select * from BookInfo", connection)) 32 { 33 //實例化數據表對象 34 DataTable dataTable = new DataTable(); 35 36 //填充數據表 37 adapter.Fill(dataTable); 38 39 //實例化工做簿對象 40 HSSFWorkbook hSSFWorkbook = new HSSFWorkbook(); 41 42 //工做簿中建立數據表,並指定名字 43 ISheet sheet = hSSFWorkbook.CreateSheet("圖書信息表"); 44 45 //生成標題行,下標爲0即第一行 46 IRow excelTile = sheet.CreateRow(0); 47 excelTile.CreateCell(0).SetCellValue("圖書編號"); 48 excelTile.CreateCell(1).SetCellValue("圖書名稱"); 49 excelTile.CreateCell(2).SetCellValue("圖書做者"); 50 51 //自定義行號,做爲自增種子,由於生變定義了標題行,因此這裏從第二行開始,即下標從1尅開始 52 int RowIndex = 1; 53 54 //將數據庫中的數據導入到Excel中 55 foreach (DataRow dataRow in dataTable.Rows) 56 { 57 IRow rowBody = sheet.CreateRow(RowIndex); 58 rowBody.CreateCell(0).SetCellValue(int.Parse(dataRow["BookId"] + "")); 59 rowBody.CreateCell(1).SetCellValue(dataRow["BookName"] + ""); 60 rowBody.CreateCell(2).SetCellValue(dataRow["Author"] + ""); 61 RowIndex++; 62 } 63 64 //實例化內存流 65 MemoryStream memoryStream = new MemoryStream(); 66 67 //將數據寫入內存流中 68 hSSFWorkbook.Write(memoryStream); 69 memoryStream.Seek(0, SeekOrigin.Begin); 70 71 //釋放適配器對象資源 72 adapter.Dispose(); 73 74 //關閉數據庫鏈接 75 connection.Close(); 76 77 //返回文件(直接下載) 78 return File(memoryStream, "application/vnd-excel", "圖書信息表.xls"); 79 } 80 } 81 } 82 } 83 }
1 @{ 2 Layout = null; 3 } 4 5 <!DOCTYPE html> 6 7 <html> 8 <head> 9 <meta name="viewport" content="width=device-width" /> 10 <title>DiplayFirstPage</title> 11 <link href="~/Content/bootstrap.css" rel="stylesheet" /> 12 </head> 13 <body> 14 <div> 15 <input type="button" name="name" value="ExportToExcel01" onclick="location.href='/Export/ExportToExcel01'" class="btn btn-success" /> 16 <hr /> 17 <input type="button" name="name" value="ExportToExcel02" onclick="location.href='/Export/ExportToExcel02'" class="btn btn-warning" /> 18 </div> 19 </body> 20 </html>