<a class="btn btn-info btn-myexcel-export" title="导出" href="javascript:;"><i class="fa fa-download"></i> 导出</a>
// 初始化表格
table.bootstrapTable({
//...
})
// 自定义导出按钮
$(document).on("click", ".btn-myexcel-export", function () {
var page = table.bootstrapTable('getData'); // 获取页面数据
let ids = [];
let id_data = '';
// 取出当前页面的id
$.each(page,function(i,v){
ids.push(v.id)
if(i == 0){
id_data = v.id;
}else{
id_data += ','+v.id;
}
})
layer.confirm("请选择导出的选项", {
title: '导出数据',
btn: ['全部数据','当前页数据(' + ids.length + '条)'],
yes: function (index, layero) {
// 全部数据
Layer.close(index);
top.location.href="/xxx/xx/export?id_data="
},
btn2: function (index, layero) {
// 当前页面数据
top.location.href="/xxx/xx/export?id_data="+id_data
}
})
});
// 为表格绑定事件
Table.api.bindevent(table);
phpexcel的使用可参考我之前写的教程 Laravel和TP导出数据Excel
/**
* 导出Excel方法
*/
public function export()
{
$this->relationSearch = true;
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
# 关联模型
$withModel = ['user', 'store', 'house'];
# 整理数据
$this->model
->with($withModel)
->where($where)
->order($sort, $order);
# 判断是否获取指定数据
if (!empty($this->request->get('id_data'))) {
$id_data = explode(',',$this->request->get('id_data'));
$this->model->where(['house_tenant.id'=>['IN',$id_data]]);
}
$list = $this->model->select();
foreach ($list as $k => $row) {
$row->visible(['id', 'realname', 'idtype', 'idno', 'createtime']);
$row->visible(['store']);
$row->getRelation('store')->visible(['name']);
$row->visible(['housebyin']);
$row->housebyin->visible(['buildingbyin']);
}
$list = collection($list)->toArray();
$count = count($list); // 总条数
# 填充表头数据
$head = ['门店','公寓','身份证号'];
# 字母列表
$letterList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
# 找到当前脚本所在路径
$path = dirname(__FILE__);
# 实例化phpexcel
$PHPExcel = new \PHPExcel();
$PHPSheet = $PHPExcel->getActiveSheet();
# 设置表内部名称
$PHPSheet->setTitle("Sheet1");
# 设置表格数据
foreach ($head as $kk => $vv) {
$PHPSheet->setCellValue($letterList[$kk]."1", $vv);
}
# 设置宽度
$PHPSheet->getColumnDimension('A')->setWidth(20);
$PHPSheet->getColumnDimension('B')->setWidth(12);
$PHPSheet->getColumnDimension('B')->setWidth(20);
# 设置高度
for ($i = 2; $i <= $count+1 ; $i++) {
$PHPSheet->getRowDimension($i)->setRowHeight(30);
}
$num = 2; // 从第二行开始插入
# 数据填充
foreach ($list as $k => $v) {
$PHPSheet->setCellValue("A" . $num, $v['store']['name']);
$PHPSheet->setCellValue("B" . $num, $v['housebyin']['buildingbyin']['name']);
$PHPSheet->setCellValue("C" . $num, "\t" . $v['idno'] . "\t"); // 身份证处理科学计数法
$num++;
}
# 文档名称
$filename = date('YmdHis');
# 创建生成的格式
$PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, "Excel2007");
# 代入文档名称
header("Content-Disposition: attachment;filename=$filename.xlsx");
header("Content-Type: text/html;charset=utf-8");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
# 生成文件
$PHPWriter->save("php://output");
exit();
}