之前做了個項目需要導出Excel文件 ,我在網上查了許多資料,最后終於搞定了 ,現在把代碼貼到下面
先導入庫文件:將文件phpoffice放在根目錄的vendor下。獲取文件點擊:鏈接:https://pan.baidu.com/s/1G426c2sQKiJ453HZSHpeIQ 提取碼:oj6f
接下來先說下沒有圖片的方法:
1. 先在application下面的command.php中添加如下的代碼:
1 function excelExport($fileName = '', $headArr = [], $data = []) { 2 3 $fileName .= "_" . date("Y_m_d", time()) . "_".time().".xls"; 4 5 $objPHPExcel = new \PHPExcel(); 6 7 $objPHPExcel->getProperties(); 8 9 $key = ord("A"); // 設置表頭 10 11 foreach ($headArr as $v) { 12 13 $colum = chr($key); 14 15 $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v); 16 17 $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v); 18 19 $key += 1; 20 21 } 22 23 $column = 2; 24 25 $objActSheet = $objPHPExcel->getActiveSheet(); 26 27 foreach ($data as $key => $rows) { // 行寫入 28 29 $span = ord("A"); 30 31 foreach ($rows as $keyName => $value) { // 列寫入 32 33 $objActSheet->setCellValue(chr($span) . $column, $value); 34 35 $span++; 36 37 } 38 39 $column++; 40 41 } 42 43 $fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表 44 45 $objPHPExcel->setActiveSheetIndex(0); // 設置活動單指數到第一個表,所以Excel打開這是第一個表 46 47 header('Content-Type: application/vnd.ms-excel'); 48 49 header("Content-Disposition: attachment;filename='$fileName'"); 50 51 header('Cache-Control: max-age=0'); 52 53 $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 54 55 $objWriter->save('php://output'); // 文件通過瀏覽器下載 56 57 exit(); 58 }
然后在你的控制器中添加如下的代碼:
1 public function excel() 2 { 3 4 5 $name='定制訂單列表'; 6 $header=['序號','客戶','日期','品類','價格','訂單屬性','客戶來源','新老客戶','顧問','所屬店鋪']; 7 /*需要哪張表的數據就查詢哪張表的數據*/ 8 $list = DB::name('order')select(); 9 $str = array(); 10 foreach ($list as $k => $v) { 11 /*對應的數據庫信息*/ 12 $str[] = ['字段1,'字段2','字段4','字段5','字段6','字段7','字段8','字段9','字段10','字段11']; 13 } 14 $data=$str; 15 excelExport($name,$header,$data); 16 }
然后調用方法execl就可以導出你想要的數據了