為了更方便,沒基礎的伙伴更容易理解,我盡量詳細簡便 省了很多代碼,一步一步的試
自己引入檔案
1.
html 前端視圖代碼 Layui的資料系結 全部代碼
@{ Layout = null; } <html> <head> <meta charset="utf-8"> <title>查詢來料清單</title> <script src=https://www.cnblogs.com/liuchunlin/p/"~/Content/新建文本檔案.js" type="text/javascript"></script> <!-- 注意:分頁必須參考下面兩個檔案 且css后加 rel="stylesheet" media="all"--> <link href=https://www.cnblogs.com/liuchunlin/p/"~/Content/layui-v2.4.5/layui/css/layui.css" rel="stylesheet" media="all" /> <link rel="stylesheet" href=https://www.cnblogs.com/liuchunlin/p/"~/Content/layui-v2.4.5/layui/css/layui.css" media="all"> <!-- 注意:如果你直接復制所有代碼到本地,上述css路徑需要改成你本地的 --> <style type="text/css"> .layui-input { height: 30px; width: 200px; } </style> </head> <body> <script type="text/html" id="toolbarDemo"> <div class="layui-btn-container" style="float:left;"> <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="Spen">匯入清單</button> </div> <div class="layui-btn-container" style="float:left;"> <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="outdata" id="excel">匯出Excel</button> </div> </script> <table class="layui-hide" id="test" lay-filter="test" lay-size="sm"></table><!--table--> <script src=https://www.cnblogs.com/liuchunlin/p/"~/Content/layui-v2.4.5/layui/layui.js"></script> <!-- 注意:如果你直接復制所有代碼到本地,上述js路徑需要改成你本地的 --> <script> $(function () { //----------------------------表格開始---------------------------------- layui.use('table', function () { var table = layui.table; //執行一個laydate實體 var tableIns=table.render({ id: 'test',//id容器 elem: '#test',//指定元素 url: '/Left_D/Ji_jian_Load', //資料接收URL地址 ------------------------------------這個地址要換自己的 methord: 'post', cellMinWidth: 95, page: { layout: ['count'] },//更改分頁的組建的位置 height: "full-50", //這里數值越高離上面就越近 數值越低離下面就越近 limits: [10, 15, 20, 25], //顯示分頁的條數 limit: 15, //默認顯示條數 fitColumns: true, //表格自動適應螢屏 even: false, //隔行背景是否顯示 toolbar: '',//開啟表格頭部工具列區域 toolbar: '#toolbarDemo' //指向自定義工具列模板選擇器toolbar: '<div>xxx</div>' //直接傳入工具列模板字符toolbar: true //僅開啟工具列,不顯示左側模板toolbar: 'default' //讓工具列左側顯示默認的內置模板 title: '來料清單', toolbar: '#toolbarDemo', //開啟頭部工具 defaultToolbar: ['filter'], //工具列右側的圖示 cols: [[ { type: 'checkbox', title: '急檢', width: 60, align: "center" }, { field: 'ID', title: 'ID', hide: "true", width: 100, align: "center", sort: "true" }, { type: 'numbers', title: '序號' , width: 50, align: "center" }, { field: 'LH001', title: '品號' , width: 120, align: "center", sort: "true" }, //sort是否允許排序 { field: 'LH002', title: '品名' , width: 100, align: "center" }, { field: 'LH003', title: '規格' , width: 100, align: "center" }, { field: 'LH004', title: '請購-單別-單號-序號', width: 160, align: "center" }, ]], done: function (res, curr, count) { //res即為你介面回傳的資訊 //得到當前頁碼curr //得到資料總量count $("[data-field='ID']").css('display', 'none'); //隱藏ID列 ,ui里隱藏失效 } }); table.on('toolbar(test)', function (obj) { var object1 = [] var arr; var checkStatus = table.checkStatus(obj.config.id); //獲取匯出資料的ID傳給后臺 switch (obj.event) {//批量匯出功能 case 'outdata': debugger; var data =https://www.cnblogs.com/liuchunlin/p/ checkStatus.data; if (data != "" && data != null) { for (var i = 0; i < data.length; i++) { //回圈拿到選擇的資料放進陣列 var id = data[i].ID; object1.push(id); arr = object1.join(','); //用逗號將資料隔開 } $.ajax({ url: "/Left_D/OutData1", type: "post", //提交方式 data: { arr: arr //傳陣列給后臺 }, success: function (data) { window.location.href = "/Left_D/DataExcel1"; //轉到匯出方法 } }); } else { layer.msg('請選擇匯出的資料'); return; } }; }); });</script> </body> </html>
前端效果圖
using System.Collections.Generic;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

2.Controller
控制器后臺代碼 不懂參考檔案在下面第3點,這里我是前臺選取ID傳進陣列,放到后臺去通過ID查詢資料
//批量匯出 [HttpPost] public void OutData1() { string time = Convert.ToDateTime(DateTime.Now).ToString(); string[] splist; string danhao = Request["arr"]; splist = null; splist = danhao.Split(','); List<L_Ji_jian> data = https://www.cnblogs.com/liuchunlin/p/bll.OutData1(splist); //資料源拿到資料 XSSFWorkbook workbook = new XSSFWorkbook(); //創建一個excel XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet(); //創建一個sheet IRow frow0 = sheet.CreateRow(0); // 添加一行(一般第一行是表頭) frow0.CreateCell(0).SetCellValue("品號"); //表頭內容 frow0.CreateCell(1).SetCellValue("品名"); frow0.CreateCell(2).SetCellValue("規格"); frow0.CreateCell(3).SetCellValue("請購單別單號序號"); for (int i = 0; i < data.Count; i++) //回圈添加list中的內容放到表格里 { IRow row = sheet.CreateRow(i + 1); //之所以從i+1開始 因為第一行已經有表頭了 row.CreateCell(0).SetCellValue(data[i].LH001); row.CreateCell(1).SetCellValue(data[i].LH002); row.CreateCell(2).SetCellValue(data[i].LH003); row.CreateCell(3).SetCellValue(data[i].LH004); } var path = System.AppDomain.CurrentDomain.BaseDirectory; //獲得專案的基目錄 var Path = System.IO.Path.Combine(path, @"Uploads\Excel\\"); //進到基目錄錄找“Uploadss->Excel”檔案夾 if (!System.IO.Directory.Exists(Path)) //判斷是否有該檔案夾 System.IO.Directory.CreateDirectory(Path); //如果沒有在Uploads檔案夾下創建檔案夾Excel string saveFileName = Path + "\\" + "來料清單資訊表" + ".xlsx"; //路徑+表名+檔案型別 try { using (FileStream fs = new FileStream(saveFileName, FileMode.Create, FileAccess.Write)) { workbook.Write(fs); //寫入檔案 workbook.Close(); //關閉 } } catch (Exception ex) { Response.Write("<script>alert('錯誤資訊:" + ex.Message + "');</script>"); } }
//呼叫瀏覽器匯出 public void DataExcel1(object sender, EventArgs e) { string fileName = "來料清單資訊表" + ".xlsx";//客戶端保存的檔案名 var path = System.AppDomain.CurrentDomain.BaseDirectory; //獲得專案的基目錄 string sering = path + "\\Uploads\\Excel\\" + fileName; //自定義服務器路徑 + 檔案名 //以字符流的形式下載檔案 FileStream fs = new FileStream(sering, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); Response.ContentType = "application/octet-stream"; //通知瀏覽器下載檔案而不是打開 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); }
2-1.BLL

2-2.DAL

2-3.




專案檔案在控制器這層 新建檔案夾Uploade--》Excel ,如果沒有代碼自己創建
3.

基本就完成了,點擊匯出呼叫瀏覽器在瀏覽器下載你服務器上的Excel檔案

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/12313.html
標籤:ASP.NET
上一篇:WebApi簡介
