我想请问一下,后端生成的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');
});
};