第一步 导入库文件
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
第二步 实例化表格并写入数据
// 1. 设置excel表格的头部
$spreadSheet = new Spreadsheet();
$sheet = $spreadSheet->getActiveSheet();
$sheet->setTitle($user['nickname'] . '的下级会员表');
$sheet->setCellValue('A1', 'ID');
$sheet->setCellValue('B1', '昵称');
$sheet->setCellValue('C1', '手机');
$dataArr = [
[
'id' => '1',
'nickname' => '小明',
'mobile' => 'XXX'
],
[
'id' => '2',
'nickname' => '小红',
'mobile' => 'XXX'
]
];
// 2.数据写入
forEach($dataArr as $key=>$item)
{
$num = $key + 2;
$sheet->setCellValue('A' . $num, $item['id']);
$sheet->setCellValue('B' . $num, $item['nickname']);
$sheet->setCellValue('C' . $num, $item['mobile']);
}
第三步 设置文件名,设置响应头
$filename = '文件名';
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
header('Cache-Control: max-age=0');
$writer = new Csv($spreadSheet);
$writer->save('php://output');
删除生成的csv文件,避免占用服务器资源
@is_file($filename . '.csv') && @unlink($filename . '.csv');
注意:该方法需由url请求触发,通过ajax请求则会在浏览器直接打印,不会以浏览器下载文件的方式导出;