在一般的系統開發中,將表格數據導出爲Excel是一項常見的功能。導出Excel分爲三種情況,第一種情況是導出當前頁的數據,第二種情況是導出當前頁已選擇的數據,第三種情況是導出全部數據。前兩種情況大致相同,本質上可歸爲一類,因爲它們都只是針對當前頁的數據進行操作,一般可在前端直接進行JSON到Excel的轉換。而第三種情況則略微複雜一些,因爲大多數情況下我們會使用服務器端分頁對數據進行展示。下面以Bootstrap-Table爲例進行說明,我在這裏做了一個例子,如下圖所示:
測試數據
前端代碼
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8" />
<title>Bootstrap-Table導出Excel</title>
<link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<link href="lib/bootstrap-table/bootstrap-table.min.css" rel="stylesheet" />
<script src="lib/bootstrap/js/jquery-3.4.1.min.js"></script>
<script src="lib/bootstrap/js/bootstrap.min.js"></script>
<script src="lib/bootstrap-table/bootstrap-table.min.js"></script>
<script src="lib/bootstrap-table/bootstrap-table-zh-CN.min.js"></script>
</head>
<body>
<div style="width:1000px;margin:200px auto;">
<div id="toolbar" class="btn-group">
<a class="btn btn-primary" href="ashx/ExportHandler.ashx">導出全部數據</a>
</div>
<table id="table"></table>
</div>
<script>
$(document).ready(function () {
$('#table').bootstrapTable({
url: "ashx/GetDataHandler.ashx", // URL
method: "post", // 請求類型
contentType: "application/x-www-form-urlencoded", // post請求必須要有,否則後臺接受不到參數
toolbar: "#toolbar", // 工具條
sidePagination: "server", // 設置在服務端還是客戶端分頁
showRefresh: false, // 是否刷新按鈕
sortStable: true, // 是否支持排序
cache: false, // 是否使用緩存
pagination: true, // 是否顯示分頁
search: false, // 是否有搜索框
clickToSelect: true, // 是否點擊選中行
pageNumber: 1, // 首頁頁碼,默認爲1
pageSize: 5, // 頁面數據條數
pageList: [5, 10, 20, 30],
queryParamsType: "",
queryParams: function (params) {
return {
pageSize: params.pageSize, // 每頁記錄條數
pageNumber: params.pageNumber, // 當前頁索引
};
},
columns: [{
field: 'Id',
title: '編號',
align: "center",
halign: "center",
sortable: true
},
{
field: 'Name',
title: '姓名',
align: "center",
halign: "center"
},
{
field: 'Gender',
title: '性別',
align: "center",
halign: "center"
},
{
field: 'Age',
title: '年齡',
align: "center",
halign: "center"
}]
})
});
</script>
</body>
</html>
後臺代碼
分頁查詢
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace WebApplication1.ashx
{
/// <summary>
/// GetDataHandler 的摘要說明
/// </summary>
public class GetDataHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
// 獲取EasyUI參數
int pageNumber = int.Parse(context.Request.Params["pageNumber"]);
int pageSize = int.Parse(context.Request.Params["pageSize"]);
int total = 0;
// 獲取數量
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "select count(*) from [TPerson]";
total = Convert.ToInt32(command.ExecuteScalar());
}
// 分頁查詢
DataTable dataTable = new DataTable();
string commandText = "select * from(select row_number() over(order by Id) as RowId, *from [TPerson]) as b where b.RowId between (@pageNumber - 1) * @pageSize + 1 and @pageNumber * @pageSize order by Id";
using (SqlDataAdapter adapter = new SqlDataAdapter(commandText, ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("@pageNumber", pageNumber),
new SqlParameter("@pageSize", pageSize)
};
adapter.SelectCommand.Parameters.AddRange(parameters);
adapter.Fill(dataTable);
}
// 傳遞給前端的數據
var data = new { total = total, rows = dataTable };
context.Response.Write(JsonConvert.SerializeObject(data));
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
導出Excel
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;
namespace WebApplication1.ashx
{
/// <summary>
/// ExportHandler 的摘要說明
/// </summary>
public class ExportHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("測試文檔.xlsx"));
// 查詢全部數據
DataTable dataTable = new DataTable();
string commandText = "select * from [TPerson]";
using (SqlDataAdapter adapter = new SqlDataAdapter(commandText, ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
adapter.Fill(dataTable);
}
// 創建工作簿
NPOI.SS.UserModel.IWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("屬性表");
NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
NPOI.SS.UserModel.ICell cell = null;
// 寫入字段名
cell = row.CreateCell(0);
cell.SetCellValue("編號");
cell = row.CreateCell(1);
cell.SetCellValue("姓名");
cell = row.CreateCell(2);
cell.SetCellValue("性別");
cell = row.CreateCell(3);
cell.SetCellValue("年齡");
// 寫入字段值
for (int i = 0; i < dataTable.Rows.Count; i++)
{
row = sheet.CreateRow(i + 1);
for (int j = 0; j < dataTable.Columns.Count; j++)
{
cell = row.CreateCell(j);
cell.SetCellValue(dataTable.Rows[i][j].ToString());
}
}
// 輸出文件流
workbook.Write(context.Response.OutputStream);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
點擊導出全部數據按鈕後可以發現已經能下載Excel文件了,如下圖所示:
文件內容如下圖所示: