PHP匯出Excel表格例項
阿新 • • 發佈:2019-01-09
/** * 處理表單匯出成表格 */ public function excel_handle($a = 2) { require_once 'vendor/PHPExcel/PHPExcel.php'; $PHPExcel = new \PHPExcel(); //例項化PHPExcel類,類似於在桌面上新建一個Excel表格 $PHPSheet = $PHPExcel->getActiveSheet(); //獲得當前活動sheet的操作物件 $PHPSheet->setTitle('處理表'); //給當前活動sheet設定名稱 //表頭 //給當前活動sheet填充資料,資料填充是按順序一行一行填充的,假如想給A1留空,可以直接setCellValue(‘A1’,’’); $PHPSheet->setCellValue('A1', 'ID') ->setCellValue('B1', '姓名') ->setCellValue('C1', '手機號') ->setCellValue('D1', '業務需求') ->setCellValue('E1', '處理人姓名')->setCellValue('F1', '建立時間') ->setCellValue('G1', '是否處理') ; $order = D('Site/Handle') ->alias('h') ->join('LEFT JOIN ly_site_category AS c ON FIND_IN_SET(c.id,h.cid)') ->join('LEFT JOIN ly_admin_user AS u ON u.id = h.uid')->group('h.id') ->field('h.id,h.username,h.mobile,group_concat(distinct c.title SEPARATOR " | ") as c_title,u.username as uusername, h.create_time as create_time,is_handle') ->select(); $list = array( '0' => '待處理', '1' => '已處理', ); foreach ($order as $k1 => $v1) { $cell = $k1 + 2; if ($v1['is_handle']){ $v1['is_handle'] = '已處理'; } else { $v1['is_handle'] = '待處理'; } $PHPSheet->setCellValue('A' . $cell, $v1['id']) ->setCellValue('B' . $cell, $v1['username']) ->setCellValue('C' . $cell, $v1['mobile']) ->setCellValue('D' . $cell, $v1['c_title']) ->setCellValue('E' . $cell, $v1['uusername']) ->setCellValue('F' . $cell, date('Y-m-d H:i:s', $v1['create_time'])) ->setCellValue('G' . $cell, $v1['is_handle']) ; } switch ($a) { case '1': $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007'); //按照指定格式生成Excel檔案,‘Excel2007’表示生成2007版本的xlsx, $PHPWriter->save('handle.xlsx'); //表示在$path路徑下面生成demo.xlsx檔案 break; case '2': // 生成2007excel格式的xlsx檔案 $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel5'); //按照指定格式生成Excel檔案,‘Excel2007’表示生成2007版本的xlsx header('Content-Type: text/html;charset=utf-8'); header('Content-Type: xlsx'); header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="handle.xls"'); header('Cache-Control: max-age=0'); $PHPWriter->save("php://output"); break; } }
推薦使用 $a = 2 的匯出方式