/**
* @param array $data 数据
* @param array $title 表头
* @return bool
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception 下载文件
*/
public function _export($data,$title){
//数据
/*$data = [
['title1' => '111', 'title2' => '222'],
['title1' => '111', 'title2' => '222']
];
//表头
$title = ['第一行标题', '第二行标题'];*/
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
//表头
//设置单元格内容
$titCol = 'A';
foreach ($title as $key => $value) {
// 单元格内容写入
$sheet->setCellValue($titCol . '1', $value);
$titCol++;
}
$row = 2; // 从第二行开始
foreach ($data as $item) {
$dataCol = 'A';
foreach ($item as $value) {
// 单元格内容写入
$sheet->setCellValue($dataCol . $row, $value);
$dataCol++;
}
$row++;
}
ob_end_clean();//清除缓冲区,避免乱码
ob_start();
// 将输出重定向到客户端的网络浏览器(Xlsx)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Cache-Control: max-age=0');
// 如果您要使用IE 9,则可能需要执行以下操作
header('Cache-Control: max-age=1');
// 如果您通过SSL向IE提供服务,则可能需要执行以下操作
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
header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.date('YmdHis').'.xlsx"');
header("Content-Disposition:attachment;filename=".date('YmdHis').".xlsx");//attachment新窗口打印 inline本窗口打印
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
/* 释放内存 */
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
ob_end_flush();
return true;
}
暂无评论