天天看点

TP5使用phpExcel输出excel文件,文件名格式和拓展名不匹配,文件乱码

在header()函数调用之前添加如下两个函数来清除错误BOM头

ob_end_clean();
ob_start();
           

完整导出代码如下

/**
 * @param string $fileName   导出文件名
 * @param array  $headArr    表头名称
 * @param array  $data       对应二维数组的数据
 * @param array  $dataHeader 对应表头的数据字段名
 */
function excelExport($fileName = '', $headArr = [], $data = [], $dataHeader = [])
{

    $fileName .= "_" . ".xls";

    $objPHPExcel = new PHPExcel();

    $objPHPExcel->getProperties();

    $key = ord("A"); // 设置表头

    foreach ($headArr as $v) {

        $colum = chr($key);

        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);

        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);

        $key += 1;

    }

    $column = 2;

    $objActSheet = $objPHPExcel->getActiveSheet();

    foreach ($data as $key => $rows) { // 行写入

        $span = ord("A");

        foreach ($rows as $keyName => $value) { // 列写入
            foreach ($dataHeader as $head) {
                if ($head == $keyName) {
                    $objActSheet->setCellValue(chr($span) . $column, $value);

                    $span++;
                }
            }


        }

        $column++;

    }

    $fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表

    $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表

    ob_end_clean();
    ob_start();

    header('Content-Type: application/vnd.ms-excel;charset=UTF-8');

    header("Content-Disposition: attachment;filename='$fileName'");

    header('Cache-Control: max-age=0');

    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

    $objWriter->save('php://output'); // 文件通过浏览器下载

}