PHP ajax 資料匯出
阿新 • • 發佈:2018-11-26
php
public function excel(Request $request) { $data = [];//匯出資料 $objPHPExcel = new \PHPExcel(); $objPHPExcel->getProperties()->setCreator('http://www.phpernote.com') ->setLastModifiedBy('http://www.phpernote.com') ->setTitle('Office 2007 XLSX Document') ->setSubject('Office 2007 XLSX Document') ->setDescription('Document for Office 2007 XLSX, generated using PHP classes.') ->setKeywords('office 2007 openxml php') ->setCategory('Result file'); $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A1','ID') ->setCellValue('B1','表頭') ->setCellValue('C1','表頭1'); $i=2; foreach ($data as $k=>$v){ $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A'.$i,$v['id']) ->setCellValue('B'.$i,$v['xx']) ->setCellValue('C'.$i,$v['yy']); $i++; } $table = "tableName"; $objPHPExcel->getActiveSheet()->setTitle($table); $objPHPExcel->setActiveSheetIndex(0); $filename=urlencode($table); //生成xlsx檔案 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="'.$filename.'.xlsx"'); header('Cache-Control: max-age=0'); $objWriter=\PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007'); $filePath = 'uploads/excel/'.$filename.'.xlsx';//儲存檔案路徑 $objWriter->save(ROOT_PATH.$filePath); // dump($filePath);exit; return echoOk(['url'=>DOMAIN."/".$filePath]); }
html
<a id="excelData" class="layui-btn layui-btn-normal">匯出excel</a>
js
<script type="text/javascript"> layui.use(['upload','form','laydate','table',['layer']],function () { var table = layui.table; var layer = layui.layer; var form = layui.form; var laydate = layui.laydate; //匯出 $("#excelData").click(function (data) { //修改狀態 $.ajax({ url: '{:url("excel")}', data: { <!--//攜帶引數--> }, type: 'post', cache: false, dataType: 'json', success: function (data1) { if (data1['status'] == 1) { console.debug(data.data); window.location.href = data1.data.url; layer.msg(data1['msg'],{time:3000}); } else { layer.msg(data1['msg'],{time:3000}); } }, error: function () { } }); }); }); </script>