setSearch()) ->field('id,card_no,card_pass') ->select() ->toArray(); return GiftCardQrCodeService::batchGenerateQrCode($giftCards); } // ... existing code ... /** * @notes 搜索条件 * @return array * @author cjhao * @date 2021/7/22 10:51 */ public function setSearch(): array { $where = []; $params = $this->params; //下单时间 if (isset($params['start_time']) && $params['start_time'] != '') { $where[] = ['create_time', '>=', strtotime($params['start_time'])]; } if (isset($params['end_time']) && $params['end_time'] != '') { $where[] = ['create_time', '<=', strtotime($params['end_time'])]; } $where[]=['gc_id','=',$params['id']]; if(isset($params['card_no'])){ $where[] = ['card_no', 'like', '%' . $params['card_no'] . '%']; } if(isset($params['is_used'])){ $where[] = ['is_used', '=', $params['is_used']]; } return $where; } /** * @notes 统计信息 * @return array * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException * @author cjhao * @date 2021/7/22 10:51 */ public function extend(): array { return []; } /** * @notes 礼品卡列表 * @return array * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException * @author cjhao * @date 2021/7/21 18:31 */ public function lists(): array { $field = 'id,gc_id,card_no,card_pass,card_money,is_used,user_id,used_time,create_time,qr_code_path'; $lists = GiftCardInfo::field($field)->where($this->setSearch()) ->with(['user']) ->append(['is_used_desc','used_user_name','batch_no','qr_code_url']) ->limit($this->limitOffset, $this->limitLength) ->order('id', 'desc') ->select() ->toArray(); // // foreach ($lists as &$list) { // $list['qr_code_url'] = 'https://nongfa.sdshengyuekeji.cn/'.$list['qr_code_path']; // } return $lists; } /** * @notes 总数 * @return int * @author cjhao * @date 2021/7/21 18:32 */ public function count(): int { return GiftCardInfo::where($this->setSearch())->count(); } /** * @notes 设置excel表名 * @return string * @author cjhao * @date 2021/9/23 9:52 */ public function setFileName(): string { return '礼品卡列表'; } /** * @notes 设置导出字段 * @return array * @author cjhao * @date 2021/9/23 9:59 */ public function setExcelFields(): array { return [ 'batch_no' => '批次', 'card_no' => '礼品卡卡号', 'card_pass' => '礼品卡密码', 'card_money' => '礼品卡价值', 'is_used_desc' => '是否使用', 'used_user_name' => '使用人', 'used_time' => '使用时间', 'create_time'=> '创建时间', 'qr_code_url' => '小程序码', // 添加小程序码字段 ]; } /** * @notes 创建包含图片的excel * @param $excelFields * @param $lists * @return string * @throws \PhpOffice\PhpSpreadsheet\Exception * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception */ public function createExcel($excelFields, $lists) { $title = array_values($excelFields); $letter_column = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']; $data = []; foreach ($lists as $row) { $temp = []; foreach ($excelFields as $key => $excelField) { $fieldData = $row[$key]; if(is_numeric($fieldData) && strlen($fieldData) >= 11){ $fieldData.="\t"; } $temp[$key] = $fieldData; } $data[] = $temp; } $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); //设置单元格内容 foreach ($title as $key => $value) { // 单元格内容写入 $sheet->setCellValueByColumnAndRow($key + 1, 1, $value); } //设置行高 $spreadsheet->getActiveSheet()->getRowDimension(1)->setRowHeight(25); $row = 2; //从第二行开始 $qrCodeColumnIndex = array_search('qr_code_url', array_keys($excelFields)); // 获取二维码列的索引 // 创建临时目录 $tempDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'excel_qr_codes'; if (!is_dir($tempDir)) { mkdir($tempDir, 0755, true); } foreach ($data as $rowIndex => $item) { $column = 1; foreach ($item as $key => $value) { $columnIndex = $column - 1; // 如果是二维码列且有URL,插入图片 if ($key === 'qr_code_url' && !empty($value)) { try { // 设置单元格为空,为图片腾出空间 $sheet->setCellValueByColumnAndRow($column, $row, ''); // 创建临时文件路径 $tempFile = $tempDir . DIRECTORY_SEPARATOR . 'qr_' . $rowIndex . '_' . time() . '_' . mt_rand(1000, 9999) . '.png'; // 下载图片到临时文件 $context = stream_context_create([ 'http' => [ 'timeout' => 10, 'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ] ]); $imageContent = @file_get_contents($value, false, $context); if ($imageContent !== false && strlen($imageContent) > 0) { // 写入临时文件 if (file_put_contents($tempFile, $imageContent) !== false && file_exists($tempFile)) { // 验证是否为有效图片 $imageInfo = @getimagesize($tempFile); if ($imageInfo !== false) { // 创建图片对象 $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); $drawing->setName('QR Code'); $drawing->setDescription('小程序码'); $drawing->setPath($tempFile); $drawing->setHeight(60); // 设置图片高度 $drawing->setWidth(60); // 设置图片宽度 // 设置图片位置 $cellCoordinate = $letter_column[$columnIndex] . $row; $drawing->setCoordinates($cellCoordinate); $drawing->setOffsetX(5); // X轴偏移 $drawing->setOffsetY(5); // Y轴偏移 // 将图片添加到工作表 $drawing->setWorksheet($sheet); // 设置行高以适应图片 $spreadsheet->getActiveSheet()->getRowDimension($row)->setRowHeight(70); } else { // 图片无效,显示URL $sheet->setCellValueByColumnAndRow($column, $row, '图片无效'); @unlink($tempFile); } } else { // 文件写入失败,显示URL $sheet->setCellValueByColumnAndRow($column, $row, '文件写入失败'); } } else { // 如果图片下载失败,显示提示 $sheet->setCellValueByColumnAndRow($column, $row, '图片下载失败'); } } catch (\Exception $e) { // 如果图片插入失败,显示错误信息 $sheet->setCellValueByColumnAndRow($column, $row, '图片处理失败: ' . $e->getMessage()); } } else { // 普通文本数据 $value = strpos($value, '=') === 0 ? " " . $value : $value; $sheet->setCellValueByColumnAndRow($column, $row, $value); } // 设置列宽 $columnWidth = ($key === 'qr_code_url') ? 15 : max([strlen($value) * 1.2, 15]); $spreadsheet->getActiveSheet()->getColumnDimension($letter_column[$columnIndex])->setWidth($columnWidth); $column++; } // 设置默认行高 if (!isset($qrCodeColumnIndex) || empty($data[$rowIndex]['qr_code_url'])) { $spreadsheet->getActiveSheet()->getRowDimension($row)->setRowHeight(25); } $row++; } $getHighestRowAndColumn = $sheet->getHighestRowAndColumn(); $HighestRow = $getHighestRowAndColumn['row']; $columnLetter = $getHighestRowAndColumn['column']; $titleScope = 'A1:' . $columnLetter . '1';//第一(标题)范围 // 设置标题样式 $sheet->getStyle($titleScope) ->getFill() ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID) ->getStartColor() ->setARGB('26956d'); $sheet->getStyle($titleScope)->getFont()->getColor() ->setARGB('FFFFFF'); $allScope = 'A1:' . $columnLetter . $HighestRow; // 设置居中对齐 $styleArray = [ 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]; $sheet->getStyle($allScope)->applyFromArray($styleArray); // 设置边框 $sheet->getStyle($allScope)->getBorders()->getAllBorders() ->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx'); //创建excel文件 $exportCache = new \app\common\cache\ExportCache(); $src = $exportCache->getSrc(); if (!file_exists($src)) { mkdir($src, 0775, true); } $writer->save($src . $this->fileName); // 清理临时文件 $this->cleanupTempFiles($tempDir); //设置本地excel缓存并返回下载地址 return (string)(url('index/download/export', ['file' => $exportCache->setFile($this->fileName)], true, true)); } /** * @notes 清理临时文件 * @param string $tempDir */ private function cleanupTempFiles($tempDir) { if (is_dir($tempDir)) { $files = glob($tempDir . DIRECTORY_SEPARATOR . '*'); foreach ($files as $file) { if (is_file($file)) { @unlink($file); } } @rmdir($tempDir); } } }