PHP中使用PhpSpreadsheet 讀取mysql ,生成excel下載
阿新 • • 發佈:2018-11-04
安裝phpoffice/phpspreadsheet
composer require phpoffice/phpspreadsheet
github地址: https://github.com/PHPOffice/PhpSpreadsheet
PhpSpreadsheet's documentation相關文件:https://phpspreadsheet.readthedocs.io/en/develop/
使用範例(範例使用ThinkPHP5.0框架)
/** * 表格資料匯出 */ public function export_excel() { //獲取任務對應的表名,以及採集資料id $param = $this->request->param(); $id = $param['id']; $info = Db::name('crawler_task')->where('id', $id)->find(); $table_name = $info['table_name']; $crawler_id = json_decode($info['crawler_id'], true); //獲取資料 $data = Db::table($info['table_name'])->whereIn('id', $crawler_id)->select()->toArray(); //獲取表資訊 $sql = "SHOW FULL COLUMNS FROM $table_name"; $table_structure = Db::table($table_name)->query($sql); $table_field = array_column($table_structure, 'Field'); $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); $field_len = count($table_field); $end_alpha = chr(63 + $field_len); // 設定表標題名稱 $worksheet->setTitle($info['task_name']); //迴圈填充第一行資料 foreach ($table_structure as $key => $value) { if ($value['Field'] != 'id') { //去除id表頭 $worksheet->setCellValueByColumnAndRow($key, 1, $value['Field']); } } //設定第一行樣式 $styleArray = [ 'font' => [ 'bold' => true ], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, ], ]; $worksheet->getStyle('A1:' . $end_alpha . '1')->applyFromArray($styleArray)->getFont()->setSize(14); //填充表資料 $len = count($data); for ($i = 0; $i < $len; $i++) { $j = $i + 2; foreach ($table_field as $key => $value) { if ($key != 0) { //去除id資料 $worksheet->setCellValueByColumnAndRow($key, $j, $data[$i][$value]); } } } //設定資料表格樣式 $styleArrayBody = [ 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, 'color' => ['argb' => '666666'], ], ], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, ], ]; $total_rows = $len + 1; //新增所有邊框/居中 $worksheet->getStyle('A1:' . $end_alpha . $total_rows)->applyFromArray($styleArrayBody); $file_name = $info['task_name'] . ".xls"; header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename=' . $file_name ); header('Cache-Control: max-age=0'); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls'); $writer->save('php://output'); }