thinkphp5.0 通过phpspreadsheet导出到excel

首先,进入thinkphp的根目录

修改为国内源composer config repo.packagist composer https://packagist.phpcomposer.com

然后composer require phpoffice/phpspreadsheet

最后就是在thinkphp中引入使用了。

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

写excel

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'id编号');
$sheet->setCellValue('B1', '姓名');
$sheet->setCellValue('C1', '手机号码');

$count = count($data);  //计算有多少条数据
for ($i = 2; $i <= $count+1; $i++) {
	$sheet->setCellValue('A' . $i, $data[$i-2]['id']); 
	$sheet->setCellValue('B' . $i, $data[$i-2]['name']); 
	$sheet->setCellValue('C' . $i, $data[$i-2]['mobile']); 
}

导出下载

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.'信息'.'.xlsx"');
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;

 

你可能感兴趣的:(thinkphp)