/**
* Export data to an Excel file.
*
* @param array $title An array of column titles.
* @param array $data An array of data rows.
* @param string $fileName The name of the file to save.
* @param string $savePath The path where the file should be saved.
* @param bool $isDown Whether the file should be downloaded.
*
* @return string The URL of the saved file.
*/functionexportExcel(array $title, array $data, string $fileName ='', string $savePath ='', bool $isDown =false): string
{// Create a new PHPExcel object
$objPHPExcel =newPHPExcel();// Set the sheet title
$objPHPExcel->getActiveSheet()->setTitle('Sheet1');// Add the title row
$titleCount =count($title);if($titleCount >0){
$objPHPExcel->getActiveSheet()->fromArray([$title],null,'A1');
$objPHPExcel->getActiveSheet()->getStyle('A1:'. $cellName[$titleCount -1].'1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->freezePane('A2');}// Add the data rowsif(!empty($data)){
$objPHPExcel->getActiveSheet()->fromArray($data,null,'A2');}// Set the filename and pathif(empty($fileName)){
$fileName =uniqid(time(),true);}
$fileName = $fileName .'.xlsx';
$savePath =rtrim($savePath,'/').'/'. $fileName;
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
$objWriter->save($savePath);// Return the URL of the saved filereturn'https://www.example.com/'. $fileName;}
调用方法
//这是我的调用//复制导出具体数据按实际要求来publicfunctionexport($data){// Get the channel IDs to export
$channelIds =implode(',', $data['id']);// Define the column headers for the exported data
$headers =['渠道名称','渠道负责人','电话','渠道行业','平台方式','业务模式'];// Define the file name for the exported file
$fileName ='channel-'.time();// Query the database to get the data to export
$rows =db('channel')->field('a.name, a.username, a.phone, b.name industry_name, c.name enter_name, d.name business_name')->alias('a')->join('dock_channel_industry b','a.industry_id = b.id','left')->join('dock_channel_enter c','a.enter_id = c.id','left')->join('dock_channel_business d','a.business_id = d.id','left')->where(['a.id'=>['in', $channelIds]])->select();// Define the save path for the exported file
$savePath =ROOT_PATH.'public'.DS.'uploads/';// Call the `exportExcel` function to generate the Excel file and get the URL of the exported file
$url =exportExcel($headers, $rows, $fileName, $savePath);// Return the URL of the exported file as a JSON response
echo json_encode(['code'=>200,'data'=> $url]);}