一、在控制器文件顶端添加以下引用
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
二、在控制器中添加下面的export方法
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');
$columns = $this->request->post('columns');
$excel = new Spreadsheet();
$excel->getProperties()
->setCreator("FastAdmin")
->setLastModifiedBy("FastAdmin")
->setTitle("标题")
->setSubject("Subject");
$excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
$excel->getDefaultStyle()->getFont()->setSize(12);
$excel->getDefaultStyle()->applyFromArray(
array(
'fill' => array(
'type' => Fill::FILL_SOLID,
'color' => array('rgb' => '000000')
),
'font' => array(
'color' => array('rgb' => "000000"),
),
'alignment' => array(
'vertical' => Alignment::VERTICAL_CENTER,
'horizontal' => Alignment::HORIZONTAL_CENTER,
'indent' => 1
),
'borders' => array(
'allborders' => array('style' => Border::BORDER_THIN),
)
));
$worksheet = $excel->setActiveSheetIndex(0);
$worksheet->setTitle('标题');
$whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
$this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$line = 1;
$list = [];
$this->model
->field($columns)
->where($where)
->where($whereIds)
->chunk(100, function ($items) use (&$list, &$line, &$worksheet) {
$styleArray = array(
'font' => array(
'color' => array('rgb' => '000000'),
'size' => 12,
'name' => 'Verdana'
));
$list = $items = collection($items)->toArray();
foreach ($items as $key => $v) {
foreach ($v as $k => $ele) {
$tmparray = explode("_text",$k);
if(count($tmparray)>1){
$items[$key][$tmparray[0]] = $ele;
unset($items[$key][$k]);
}
}
}
foreach ($items as $index => $item) {
$line++;
$col = 0;
foreach ($item as $field => $value) {
$worksheet->setCellValueByColumnAndRow($col, $line, $value);
$worksheet->getStyleByColumnAndRow($col, $line)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
$worksheet->getCellByColumnAndRow($col, $line)->getStyle()->applyFromArray($styleArray);
$col++;
}
}
});
$first = array_keys($list[0]);
foreach ($first as $k => $ele) {
$tmparray = explode("_text",$ele);
if(count($tmparray)>1){
unset($first[$k]);
}
}
foreach ($first as $index => $item) {
$worksheet->setCellValueByColumnAndRow($index, 1, __($item));
}
$excel->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
$objWriter = IOFactory::createWriter($excel, 'Xlsx');
$objWriter->save('php://output');
return;
}
}
三、在index.html中添加“导出按钮”
<a href="javascript:;" class="btn btn-success btn-export {:$auth->check('stock/stockin/export')?'':'hide'}" title="{:('Export')}" id="btn-export-file"><i class="fa fa-download"></i> {:('Export')}</a>
四、修改相对应的js文件
找到
// 为表格绑定事件
Table.api.bindevent(table);
复制以下代码放到该行上面:
//自定义export开始
var submitForm = function (ids, layero) {
var options = table.bootstrapTable('getOptions');
console.log(options);
var columns = [];
$.each(options.columns[0], function (i, j) {
if (j.field && !j.checkbox && j.visible && j.field != 'operate') {
columns.push(j.field);
}
});
var search = options.queryParams({});
$("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(','));
$("form", layero).submit();
};
$(document).on("click", ".btn-export", function () {
var ids = Table.api.selectedids(table);
var page = table.bootstrapTable('getData');
var all = table.bootstrapTable('getOptions').totalRows;
console.log(ids, page, all);
Layer.confirm("请选择导出的选项<form action='" + Fast.api.fixurl("test/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='search'><input type='hidden' name='columns'></form>", {
title: '导出数据',
//btn: ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
btn: ["选中项(" + ids.length + "条)"],
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;
}
})
});
//*************************** 自定义export结束
// 为表格绑定事件
Table.api.bindevent(table);
设置ID第一列
以上内容为摘抄,如有侵权请告知