/*
* $list 二维数组 数据
* $headerArr 第一行标题
* $excelTitle Excel文件标题
* $save_fileUrl 文件名 注意后缀名
*/
function outputDataToExcelFile($list = [], $headerArr = [], $excelTitle = "", $save_fileUrl = "")
{
//实例化PHPExcel类
$objPHPExcel = new PHPExcel();
//设置头信息 激活当前的sheet表
$objPHPExcel->setActiveSheetIndex(0);
$keyC = ord('A');
foreach ($headerArr as $head) {
$colKey = chr($keyC);
//$objPHPExcel->getActiveSheet()->mergeCells('A1:Q1');
//TODO 设置表格头(即excel表格的第一行)
//A1 、B1 、C1
$objPHPExcel->getActiveSheet()->setCellValue($colKey . '1', $head);
//自动换行
$objPHPExcel->getActiveSheet()->getStyle($colKey)->getAlignment()->setWrapText(true);
//居中
//$objPHPExcel->getActiveSheet()->getStyle($colKey)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
//设置单元格宽度
$objPHPExcel->getActiveSheet()->getColumnDimension($colKey)->setWidth(100);
$keyC++;
}
//第3行开始
$colIndex = 1;
foreach ($list as $key => $rows) {
$colKey2 = ord('A');
foreach ($list[$key] as $keyName => $value) {
// \t \t 强制转移为字符串形式 避免被科学计数
//$c = iconv("UTF-8", "GBK", $value);
$objPHPExcel->getActiveSheet()->setCellValue(chr($colKey2) . $colIndex, "\t".$value."\t");
$colKey2++;
}
$colIndex++;
}
//设置当前激活的sheet表格名称;
$objPHPExcel->getActiveSheet()->setTitle($excelTitle);
//清空缓存 避免乱码
//ob_end_clean();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//写入文件
//$save_fileUrl = '123';
$objWriter->save($save_fileUrl);
//设置浏览器窗口下载表格
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Type: application/vnd.ms-excel;charset=UTF-8');
header('Content-Disposition:inline;filename="' . $save_fileUrl . '"');
//下载文件在浏览器窗口
$objWriter->save('php://output');
exit;
}
phpexcel操作
最新推荐文章于 2024-01-19 09:00:00 发布