之前写的导出,今天发现了个bug,如果导出的数据列数超过26列会报错:Invalid cell coordinate [1,所以,还得改:
/**
* excel表格导出
* @param string $fileName 文件名称
* @param array $headArr 表头名称
* @param array $data 要导出的数据
* @author mrLv
*/
function excelExport($fileName = '', $headArr = [], $data = []) {
$fileName .= "_" . date("Y_m_d", time()) . ".xls";
$spreadsheet = new Spreadsheet();
$objPHPExcel = $spreadsheet->getActiveSheet();
$key = ord("A"); // 设置表头
$key2 = ord("@");
foreach ($headArr as $v) {
if($key > ord("Z")){
$key2 += 1;
$key = ord("A");
$colum = chr($key2).chr($key);
}else{
if($key2>=ord("A")){
$colum = chr($key2).chr($key);
}else{
$colum = chr($key);
}
}
$objPHPExcel->setCellValue($colum . '1', $v);
$key += 1;
}
$column = 2;
foreach ($data as $key => $rows) { // 行写入
$span = ord("A");
$span2 = ord("@");
foreach ($rows as $keyName => $value) { // 列写入
if($span > ord("Z")){
$span2 += 1;
$span = ord("A");
$j = chr($span2).chr($span);
}else{
if($span2>=ord("A")){
$j = chr($span2).chr($span);
}else{
$j = chr($span);
}
}
$objPHPExcel->setCellValue($j . $column, $value);
$span++;
}
$column++;
}
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;
}
注意黑色加粗的代码!