目標:使用php,經過ajax請求的方式生成一個excel,而後下載。php
思路:大體思路是發送一個ajax請求到後臺,後臺php處理後生成一個excel文件,而後把生成的文件放到一個臨時目錄,而後把文件連接返回給前端。前端接受到後,而後經過給定的地址,去下載該文件....html
代碼實現:前端
前端部分:ajax
<pre name="code" class="html">function outExcel(){
var allSelect = $('._newId:checked').length;
if(allSelect == 0){
layer.msg('請選擇須要導出的記錄');
return false;
}
var ids = [];
$('._newId:checked').each(function(){
ids.push($(this).val());
});
var params = {id:ids};
$.post("{:U('Home/Saidi/outExcel')}",params,function(res){
if(res.status){
window.location.href = ("{:U('Home/Saidi/download')}?file="+res.url+'&token='+res.token);
}else{
layer.msg('系統錯誤,操做失敗');
}
},'json');
}json
其中token是用來作安全校驗的.....
後臺部分:安全
使用的是PHPExcel插件。這裏用的是TP框架app
public function outExcel(){
$ids = I('post.id','','trim');
if(empty($ids)){
exit(json_encode(array('status'=>false,'url'=>'','token'=>'')));
}
$where['id'] = array('in',$ids);
$data = M('news','xyl_')->where($where)->select();
if(!empty($data)){
Vendor('PHPExcel.PHPExcel');
Vendor('PHPExcel.PHPExcel.IOFactory');
$phpExcel = new \PHPExcel();
$phpExcel->setActiveSheetIndex(0)
->setCellValue('A1', '序號')
->setCellValue('B1', '新聞標題')
->setCellValue('C1', '新聞摘要')
->setCellValue('D1', '新聞內容')
->setCellValue('E1', '新聞來源')
->setCellValue('F1', '做者')
->setCellValue('G1', '來源網址');
$len = count($data);
for($i = 0 ; $i < $len ; $i++){
$v = $data[$i];
$rownum = $i+2;
$phpExcel->getActiveSheet()->setCellValue('A' . $rownum, $i);
$phpExcel->getActiveSheet()->setCellValue('B' . $rownum, $v['title']);
$phpExcel->getActiveSheet()->setCellValue('C' . $rownum, $v['summary']);
$phpExcel->getActiveSheet()->setCellValue('D' . $rownum, $v['content']);
$phpExcel->getActiveSheet()->setCellValue('E' . $rownum, $v['from']);
$phpExcel->getActiveSheet()->setCellValue('F' . $rownum, $v['author']);
$phpExcel->getActiveSheet()->setCellValue('G' . $rownum, $v['url']);
}
$phpExcel->setActiveSheetIndex(0);
$filename=date('YmdHis').'.xlsx';
$objWriter=\PHPExcel_IOFactory::createWriter($phpExcel,'Excel2007');
$filePath = C('TMP_PATH').$filename;
$objWriter->save($filePath);
if(!file_exists($filePath)){
$response = array(
'status' => false,
'url' => '',
'token'=>''
);
}else{
$response = array(
'status' => true,
'url' => $filename,
'token'=>$this->getDownLoadToken($filename)
);
}
}else{
$response = array(
'status' => false,
'url' => '',
'token'=>''
);
}
exit(json_encode($response));
}
private function getDownLoadToken($filename,$length = 10){
$str = null;
$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
$max = strlen($strPol)-1;
for($i=0;$i<$length;$i++){
$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介於min和max兩個數之間的一個隨機整數
}
$res = md5($str.time());
S($res,$filename);
return $res;
}
public function download(){
$fileName = I('get.file','','trim');
$token = I('get.token','','trim');
if(empty($token) || !S($token)){
header("HTTP/1.0 404 Not Found");
exit;
}
$path = C('TMP_PATH').$fileName;
if(!file_exists($path)){
header("HTTP/1.0 404 Not Found");
exit;
}else{
$file = @fopen($path,"r");
if(!$file){
header("HTTP/1.0 505 Internal server error");
exit;
}
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: ".filesize($path));
header("Content-Disposition: attachment; filename=" . $fileName);
while(!feof($file)){
echo fread($file,2048);
}
fclose($file);
@unlink($path);
S($token,NULL);
exit();
}
}框架
getDownLoadToken這個方法是用來獲取憑證的,也就是tokenpost
原文:https://blog.csdn.net/wangyibo5843/article/details/53116717 this