tp3使用PHPExcel 导出excel

2021-01-07 04:29

阅读:845

标签:string   writer   reac   row   数据   column   date   sheet   max   

/**
 * 通用导出
 * array $data 导出数据
 * array $indexKey 导出数据键
 * array $headArr 表头
 * string $title 生成文件名
 *
 * 必须保持 $indexKey 和 $headArr 顺序对应才能保证导出数据准确
 */
function plainExportExcel($data,$indexKey,$headArr,$title)
{
    //引入核心文件
    import("Org.Util.PHPExcel");
    import("Org.Util.PHPExcel.IOFactory");
    $objPHPExcel = new \PHPExcel();
    $objWriter =  \PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel5‘);
    // 设置excel文档的属性
    $objPHPExcel->getProperties();
    $fileName = $title.date("Y-m-d",time()).".xls";
    //excel头
    $letter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK","AL","AM","AN","AO"];
    //设置表头
    $num = 0;
    foreach($headArr as $v){
        $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($letter[$num].‘1‘, $v);
        $num ++;
    }
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    //写入内容
    foreach($data as $key => $rows){
        //行写入
        $num = 0;
        foreach ($indexKey as $ki => $vi) {
            //列写入
            $objActSheet->setCellValue($letter[$num].$column, $rows[$vi]);
            $num++;
        }
        $column++;
    }

    $fileName = iconv("utf-8", "gb2312", $fileName);
    $objPHPExcel->setActiveSheetIndex(0);
    ob_end_clean();
    ob_start();
    Header(‘content-Type:application/vnd.ms-excel;charset=utf-8‘);
    header(‘Content-Type: application/vnd.ms-excel‘);
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header(‘Cache-Control: max-age=0‘);
    header(‘content-type:application/octet-stream‘);
    $objWriter->save(‘php://output‘); //文件通过浏览器下载
}

 

tp3使用PHPExcel 导出excel

标签:string   writer   reac   row   数据   column   date   sheet   max   

原文地址:https://www.cnblogs.com/yuanshen/p/13570452.html


评论


亲,登录后才可以留言!