說明#
FastAdmin 後台 Bootstrap Table 自帶的數據導出功能,通過前端渲染生成 Excel,對於少量數據導出方便,
但是大量數據導出,會造成卡頓卡死。
考慮利用 php 的 PhpSpreadsheet 封裝,後台渲染生成 Excel。
參考鏈接#
- https://ask.fastadmin.net/article/6055.html
- https://ask.fastadmin.net/question/1670.html
- https://www.cnblogs.com/xuanjiange/p/14545111.html
- https://ask.fastadmin.net/question/14012.html
- https://blog.csdn.net/qq_15957557/article/details/113607843
具體代碼#
導出按鈕#
在.html 下
<div id="toolbar" class="toolbar">
<a href="javascript:;" class="btn btn-success btn-export" title="{:__('Export')}" id="btn-export-file"><i class="fa fa-download"></i> {:__('Export')}</a>
</div>
具體 js#
通過 submitForm 方法,把 bootstrapTable 的搜索條件、排序、字段、searchList,都傳遞給後台控制器方法
//自定義導出
var submitForm = function (ids, layero) {
var options = table.bootstrapTable('getOptions');
//console.log(options);
var columns = [];
var searchList = {};
$.each(options.columns[0], function (i, j) {
if (j.field && !j.checkbox && j.visible && j.field != 'operate') {
columns.push(j.field);
//保存searchList 傳遞給後台處理
if (j.searchList){
searchList[j.field] = j.searchList;
}
}
});
var search = options.queryParams({});
//指定具體form 否則選擇條件查詢後 導出會卡一下
var form = document.getElementById('export');
$("input[name=search]", layero).val(options.searchText);
$("input[name=ids]", layero).val(ids);
$("input[name=filter]", layero).val(search.filter);
$("input[name=op]", layero).val(search.op);
$("input[name=columns]", layero).val(columns.join(','));
$("input[name=sort]", layero).val(options.sortName);
$("input[name=order]", layero).val(options.sortOrder);
$("input[name=searchList]", layero).val(JSON.stringify(searchList));
//$("form", layero).submit();
form.submit(ids, layero);
};
$(document).on("click", ".btn-export", function () {
var url = ""; //導出方法的控制器url
var ids = Table.api.selectedids(table);
var page = table.bootstrapTable('getData');
var all = table.bootstrapTable('getOptions').totalRows;
console.log(ids, page, all);
//這裡有個form表單 裡面的input 和 submitForm中對應,想傳其他參數,可以繼續增加input
Layer.confirm("請選擇導出的選項<form action='" + Fast.api.fixurl(url) + "' id='export' method='post' target='_blank'><input type='hidden' name='ids' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'><input type='hidden' name='sort'><input type='hidden' name='order'><input type='hidden' name='search'><input type='hidden' name='columns'><input type='hidden' name='searchList'></form>", {
title: '導出數據',
btn: ["選中項(" + ids.length + "條)", "本頁(" + page.length + "條)", "全部(" + all + "條)"],
success: function (layero, index) {
$(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
}
, yes: function (index, layero) {
submitForm(ids.join(","), layero);
return false;
}
,
btn2: function (index, layero) {
var ids = [];
$.each(page, function (i, j) {
ids.push(j.id);
});
submitForm(ids.join(","), layero);
return false;
}
,
btn3: function (index, layero) {
submitForm("all", layero);
return false;
}
})
});
後台控制器方法#
public function export()
{
if ($this->request->isPost()) {
set_time_limit(0);
$search = $this->request->post('search');
$ids = $this->request->post('ids');
$filter = $this->request->post('filter');
$op = $this->request->post('op');
$sort = $this->request->post('sort');
$order = $this->request->post('order');
$columns = $this->request->post('columns');
$searchList = $this->request->post('searchList');
$searchList = json_decode($searchList,true);
$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()
->setCreator("FastAdmin")
->setLastModifiedBy("FastAdmin")
->setTitle("標題")
->setSubject("Subject");
$spreadsheet->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
$spreadsheet->getDefaultStyle()->getFont()->setSize(10);
//單元格格式 文本
$spreadsheet->getDefaultStyle()->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_TEXT);
$worksheet = $spreadsheet->setActiveSheetIndex(0);
$whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
$this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op, 'sort' => $sort, 'op' => $order]);
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//$columns 是得到的字段,可以在這裡寫上自己的邏輯,比如刪除或添加其他要寫的字段
$columns_arr = explode(',',$columns);
$line = 1;
$list = [];
$this->model
->field($columns)
->where($where)
->where($whereIds)
->chunk(100, function ($items) use (&$list, &$line, &$worksheet,&$columns_arr,&$searchList) {
$list = $items = collection($items)->toArray();
foreach ($items as $index => $item) {
$line++;
$col = 1;
foreach ($item as $field => $value) {
//只導出傳遞的字段過濾createtime_text 等modeld中的附加字段
if (!in_array($field,$columns_arr)) continue;
//根據前端傳遞的$searchList 處理狀態等
if (isset($searchList[$field])){
$value = $searchList[$field][$value] ?? $value;
}
if (strlen($value) < 10){
$worksheet->setCellValueByColumnAndRow($col, $line, $value);
}else{
//防止長數字科學計數
$worksheet->setCellValueExplicitByColumnAndRow($col, $line, $value,\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
}
$col++;
}
}
},$sort,$order);
$first = array_keys($list[0]);
foreach ($first as $index => $item) {
//只導出傳遞的字段
if (!in_array($item,$columns_arr)) continue;
$worksheet->setCellValueByColumnAndRow($index + 1, 1, __($item));
//單元格自適應寬度
$spreadsheet->getActiveSheet()->getColumnDimensionByColumn($index + 1)->setAutoSize(true);
//首行加粗
$spreadsheet->getActiveSheet()->getStyleByColumnAndRow($index + 1, 1)->getFont()->setBold(true);
//水平居中
$styleArray = [
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
],
];
$spreadsheet->getActiveSheet()->getStyleByColumnAndRow($index + 1, 1)->applyFromArray($styleArray);
}
$spreadsheet->createSheet();
// Redirect output to a client’s web browser (Excel2007)
$title = date("YmdHis");
//header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
//header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
//header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
//header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
//header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
//header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
//header('Pragma: public'); // HTTP/1.0
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
//下載文檔
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
return;
}
}
不足之處#
大數據導出還是會內存溢出
- 有個輕量的 Excel 封裝,能解決內存溢出問題 https://github.com/mk-j/PHP_XLSXWriter
PHP_XLSXWriter 參考鏈接#
- https://blog.csdn.net/qq_36025814/article/details/117136435
- https://blog.csdn.net/qq_21193711/article/details/105285623
- https://github.com/mk-j/PHP_XLSXWriter
PHP_XLSXWriter 使用#
copy 用法#
- 把 xlsxwriter.class.php 文件放在目錄 根目錄 \application\common\libs 下
- 修改文件名 xlsxwriter.class.php 為 XLSXWriter.php
- 在文件中引入命名空間 namespace app\common\library;
- 把壓縮包類名:(1)、ZipArchive () 改成 \ZipArchive ();(2)、ZipArchive::CREATE 改成 \ZipArchive::CREATE
- 擴展:可把 XLSXWriter_BuffererWriter 抽出來,改成一個單獨的類 XLSXWriterBufferWriter。在 XLSXWriter.php 中調用的地方修改一下。
<?php
namespace app\common\library;
class XLSXWriter
{
}
替換之前的 export 方法#
public function export()
{
if ($this->request->isPost()) {
set_time_limit(0);
ini_set("memory_limit", "256M");
$search = $this->request->post('search');
$ids = $this->request->post('ids');
$filter = $this->request->post('filter');
$op = $this->request->post('op');
$sort = $this->request->post('sort');
$order = $this->request->post('order');
$columns = $this->request->post('columns');
$searchList = $this->request->post('searchList');
$searchList = json_decode($searchList,true);
$whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
$this->request->get(['search' => $search, 'ids' => $ids, 'filter' => urldecode($filter), 'op' => urldecode($op), 'sort' => $sort, 'order' => $order]);
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//$columns 是得到的字段,可以在這裡寫上自己的邏輯,比如刪除或添加其他要寫的字段
$columns_arr = $new_columns_arr = explode(',',$columns);
$key = array_search('serviceFee',$columns_arr);
if ($key){
$new_columns_arr[$key] = "(platformFee + agentFee)/100 AS serviceFee";
$columns = implode(',',$new_columns_arr);
}
//todo
$userInfo = $this->auth->getUserInfo();
$map = [];
//代理
if ($userInfo['level'] == \Pc::Agent_Level){
$info = model('Agent')->where([
'accname' => $userInfo['username'],
])->find();
if (!$info) $this->error(__('Permission denied'));
$map['agentID'] = $info['id'];
}
//限制商戶顯示
if ($userInfo['level'] == \Pc::Merchant_Level){
$info = model('Merchant')->where([
'accname' => $userInfo['username'],
])->find();
if (!$info) $this->error(__('Permission denied'));
$map['mid'] = $info['mid'];
}
$count = $this->model
->where($where)
->where($whereIds)
->where($map)
->count();
if ($count > 50000){
$this->error('數據量過大,建議分批導出','');
}
$title = date("YmdHis");
$fileName = $title . '.xlsx';
$writer = new \app\common\library\XLSXWriter();
$sheet = 'Sheet1';
//處理標題數據,都設置為string類型
$header = [];
foreach ($columns_arr as $value) {
$header[__($value)] = 'string'; //把表頭的數據全部設置為string類型
}
$writer->writeSheetHeader($sheet, $header);
$this->model
->field($columns)
->where($where)
->where($whereIds)
->where($map)
->chunk(1000, function ($items) use (&$list, &$writer,&$columns_arr,&$searchList) {
$list = $items = collection($items)->toArray();
foreach ($items as $index => $item) {
//根據標題數據title,按title的字段順序把數據一條條加到excel中
$sheet = 'Sheet1';
$row = [];
foreach ($item as $field => $value) {
//只導出傳遞的字段 過濾createtime_text 等modeld中的附加字段
if (!in_array($field,$columns_arr)) continue;
//根據前端傳遞的$searchList 處理狀態等
if (isset($searchList[$field])){
$value = $searchList[$field][$value] ?? $value;
}
$row[$field] = $value;
}
$writer->writeSheetRow($sheet, $row);
}
},$sort,$order);
//設置 header,用於瀏覽器下載
header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($fileName).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$writer->writeToStdOut();
exit(0);
}
}
基本使用#
<?php
use app\common\libs\XLSXWriter;
class Test {
//入口方法
public function test() {
$title = self::getTitle();
$data = self::getData();
//下載直接保存文件
// self::downloadExcel($title, $data, 'download_by_file.xlsx');
//瀏覽器彈框下載
self::downloadExcel($title, $data, 'downloadByBrowser.xlsx', 2);
}
/**
* 把數據下載為文件
* @param $title 標題數據
* @param $data 內容數據
* @param $fileName 文件名(可包含路徑)
* @param int $type Excel下載類型:1-下載文件;2-瀏覽器彈框下載
* @param string $sheet Excel的工作表
*/
public function downloadExcel($title, $data, $fileName, $type = 1, $sheet = 'Sheet1')
{
$writer = new XLSXWriter();
if ($type == 2) {
//設置 header,用於瀏覽器下載
header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($fileName).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
}
//處理標題數據,都設置為string類型
$header = [];
foreach ($title as $value) {
$header[$value] = 'string'; //把表頭的數據全部設置為string類型
}
$writer->writeSheetHeader($sheet, $header);
//根據標題數據title,按title的字段順序把數據一條條加到excel中
foreach ($data as $key => $value) {
$row = [];
foreach ($title as $k => $val) {
$row[] = $value[$k];
}
$writer->writeSheetRow($sheet, $row);
}
if ($type == 1) { //直接保存文件
$writer->writeToFile($fileName);
} else if ($type == 2) { //瀏覽器下載文件
$writer->writeToStdOut();
// echo $writer->writeToString();
exit(0);
} else {
die('文件下載方式錯誤~');
}
}
public function getData()
{
$data = [];
for ($i = 0; $i < 10; $i ++) {
$data[] = ['name' => "姓名{$i}", 'hobby' => "愛好{$i}"];
}
return $data;
}
public function getTitle()
{
return [
'name' => '姓名',
'hobby' => '愛好'
];
}
}