فهرست منبع

excel导出测试

曹鹤洋 1 سال پیش
والد
کامیت
3598145597
1فایلهای تغییر یافته به همراه23 افزوده شده و 15 حذف شده
  1. 23 15
      application/api/controller/PackagingCountDocument.php

+ 23 - 15
application/api/controller/PackagingCountDocument.php

@@ -5,6 +5,8 @@ namespace app\api\controller;
 use app\common\controller\Api;
 use PhpOffice\PhpSpreadsheet\Spreadsheet;
 use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\HttpFoundation\StreamedResponse;
 
 /**
  * 包装计件单据维护接口
@@ -640,13 +642,17 @@ class PackagingCountDocument extends Api
 //        $this->success('成功',['file_name'=>$req['file_name'],'data'=>$data]);
     }
 
-    public function Ex($file_name,$data)
+    public function Ex()
     {
         $spreadsheet = new Spreadsheet();
-
         $sheet = $spreadsheet->getActiveSheet();
+        $file_name = 'example'; // 设置默认的文件名
 
-        $sheet->setTitle($file_name);
+        // 获取需要导出的数据
+        $data = [
+            ['2022-01-01', '001', '产品A'],
+            ['2022-01-02', '002', '产品B'],
+        ];
 
         // 将数据逐行写入工作表
         foreach ($data as $rowIndex => $rowData) {
@@ -655,19 +661,21 @@ class PackagingCountDocument extends Api
                 $sheet->setCellValueByColumnAndRow($columnIndex + 1, $rowIndex + 1, $cellData);
             }
         }
-        $writer = new Xlsx($spreadsheet);
-        $save_path = 'uploads/' . $file_name . '.xlsx';
 
-        // 保存 Excel 文件到指定路径
-        $writer->save($save_path);
-
-        // 设置响应头信息
-        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
-        header('Content-Disposition: attachment; filename="' . $file_name . '.xlsx"');
-        header('Content-Length: ' . filesize($save_path));
-
-        // 输出文件内容到客户端
-        readfile($save_path);
+        // 创建 Excel 文件流
+        $writer = new Xlsx($spreadsheet);
+        $tempFilePath = tempnam(sys_get_temp_dir(), 'excel');
+        $writer->save($tempFilePath);
+
+        // 创建响应对象并设置头信息
+        $response = new StreamedResponse(function () use ($tempFilePath) {
+            readfile($tempFilePath);
+            unlink($tempFilePath);
+        });
+        $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
+        $response->headers->set('Content-Disposition', 'attachment;filename="' . $file_name . '.xlsx"');
+
+        return $response;
     }
 
 }