thinkphp导出excel
使用库:PHPOffice/PHPExcel GitHub - PHPOffice/PHPExcel: ARCHIVED
以下为核心代码:可根据具体需求更改。
1、控制器文件添加export
方法
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;
public function export()
{
if ($this->request->isPost()) {
/**
* 设置程序执行时间的函数
* 为零说明永久执行直到程序结束
*/
set_time_limit(0);
$ids = $this->request->post('ids');
$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('标题');
// 配合js,如果提交参数为all,则导出所有数据
$whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
$line = 1;
$list = [];
$this->model
->field($columns)
->where($whereIds)
// 使用分批查询
/**
* 注意点:如果使用到了with关联查询,
* 需要指定chunk分批处理的字段名(形参)
* 例如:fa_student.id fa_student表的id
* 默认为id,如果关联表也有id字段,则会抛出异常
* SQLSTATE[23000]: Column ‘id’ in where clause is ambiguous
*/
->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]);
/**
* 去除带_text的字段
* "category_text"
* "status_text"
*/
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;
}
}
2、html页面添加后按钮,在js中绑定按钮事件:
var table = $('form[role=form]');
//自定义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=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='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;
}
})
});