2 sinat 31092021 sinat_31092021 于 2016.09.06 17:23 提问

前端下载后端生成的excel文件

我想请问一下,后端生成的excel文件如何在前端下载?我下载下来之后老是乱码:这是后端生成excel文件的代码

//生成excel
function create_excel($title,$arr,$data){  
    $this->load->library('/php_excel/PHPExcel');
    // $this->load->library('/php_excel/PHPExcel/IOFactory');
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getProperties()->setTitle($title);
    $objPHPExcel->setActiveSheetIndex(0);  
    $type = 'Excel5';
    //发送标题强制用户下载文件
    $this->browser_export($type, $title); 
    $col = 0;
    //表头
    foreach ($arr as $k => $v){ 
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $v);
        $col++;
    }
    //循环获取的数据
    if($data){
        for($i=0;$i<count($data);$i++){
            $col = 0;
            $data_item=$data[$i];   
            foreach ($data_item as $key=>$value){
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $i+2, $value); 
                $col++;
            } 
        }
    } 
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,$type);  
    $objWriter->save('php://output');

} 
private function browser_export($type, $file_name){
    //发送标题强制用户下载文件
    if( $type=='Excel5' ){
        header('Content-Type: application/vnd.ms-excel;charset=UTF-8');//Excel5
        header('Content-Disposition: attachment;filename='.$file_name.'.xls');//tell browser file name 
    }else{
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8');//Excel2007
        header('Content-Disposition: attachment;filename='.$file_name.'.xlsx');//tell browser file name 
    }  
    header('Cache-Control: max-age=0');// forbid browser to cache
}

这是前端下载的代码:
$scope.downLoad = function(){ 
        var dataParams = sessionStorage.getItem('dataParams'); 
        if( !dataParams ){ return;}  
        console.log(JSON.parse(dataParams));  
        superSearchServices.downLoadExcel(JSON.parse(dataParams))
        .success(function(data){     
            var blob = new Blob([data],{'type':'application/vnd.ms-excel;charset=UTF-8'});  
            saveAs(blob,'统计excel');   
        });
    };

1个回答

caozhy
caozhy   Ds   Rxr 2016.09.07 00:11
 //设置导出文件名 

$outputFileName = 'total.xls'; 

$xlsWriter = new PHPExcel_Writer_Excel5($resultPHPExcel); 

//ob_start(); ob_flush(); 

header("Content-Type: application/force-download"); 

header("Content-Type: application/octet-stream"); 

header("Content-Type: application/download"); 

header('Content-Disposition:inline;filename="'.$outputFileName.'"'); 

header("Content-Transfer-Encoding: binary"); 

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 

header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 

header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 

header("Pragma: no-cache"); 

$xlsWriter->save( "php://output" );
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!