之前一直用的PHPExcel,最近发现composer update的时候一直提示
被放弃了。。。。。。所以转成Spreadsheet了,这里记录一下。
切到项目根目录,执行:
composer require phpoffice/phpspreadsheet
引入:
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
调用方法:
/**
* excel表格导出
* @param string $fileName 文件名称
* @param array $headArr 表头名称
* @param array $data 要导出的数据
* @author Mr.Lv 3063306168@qq.com
*/
function excelExport($fileName = '', $headArr = [], $data = []) {
$fileName .= "_" . date("Y_m_d", time()) . ".xls";
$spreadsheet = new Spreadsheet();
$objPHPExcel = $spreadsheet->getActiveSheet();
$key = ord("A"); // 设置表头
foreach ($headArr as $v) {
$colum = chr($key);
$objPHPExcel->setCellValue($colum . '1', $v);
$key += 1;
}
$column = 2;
foreach ($data as $key => $rows) { // 行写入
$span = ord("A");
foreach ($rows as $keyName => $value) { // 列写入
$objPHPExcel->setCellValue(chr($span) . $column, $value);
$span++;
}
$column++;
}
//$fileName = iconv("utf-8", "gbk//IGNORE", $fileName); // 重命名表(UTF8编码不需要这一步)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx"');
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
//删除清空:
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
exit;
}
在需要调用的地方直接调用就可以了