Sfoglia il codice sorgente

导出Excel 不再是保存到服务器,而且以流的形式返回给前端

王苗苗 5 mesi fa
parent
commit
28c42802f4

+ 88 - 13
ruoyi-admin/src/main/java/com/ruoyi/web/controller/business/BusinessController.java

@@ -4,6 +4,7 @@ import com.alibaba.excel.EasyExcel;
 import com.alibaba.excel.ExcelWriter;
 import com.alibaba.excel.write.metadata.WriteSheet;
 import com.alibaba.excel.write.metadata.fill.FillConfig;
+import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
 import com.alibaba.fastjson2.JSON;
 import com.ruoyi.business.domain.*;
 import com.ruoyi.business.mapper.*;
@@ -22,9 +23,17 @@ import io.swagger.models.auth.In;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.core.io.InputStreamResource;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.*;
+import sun.misc.CharacterEncoder;
 
 import javax.servlet.http.HttpServletResponse;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.net.URLEncoder;
 import java.util.*;
 import java.util.concurrent.atomic.AtomicReference;
 import java.util.stream.Collectors;
@@ -162,9 +171,8 @@ public class BusinessController extends BaseController {
      * 接口5:导出 通过设备编号和日期获取质控样的化验记录的明细和各个指标的偏差度等到Excel
      * @param response
      */
-//    @PostMapping("/exportAssayPageListByDeviceNoAndDate")
     @GetMapping("/exportAssayPageListByDeviceNoAndDate")
-    public R<String> exportAssayPageListByDeviceNoAndDate(HttpServletResponse response, AssayReq assayReq)
+    public ResponseEntity<InputStreamResource> exportAssayPageListByDeviceNoAndDate(HttpServletResponse response, AssayReq assayReq)
     {
         log.info("进入了 导出 通过设备编号和日期获取质控样的化验记录的明细和各个指标的偏差度等到Excel 接口,请求参数是{}", JSON.toJSONString(assayReq));
         DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
@@ -175,8 +183,8 @@ public class BusinessController extends BaseController {
 //        String templateFilePath = "classpath:/assay-record.xlsx";
         // 输出文件路径
 //        String outFilePath = "/Users/wangmiaomiao/Desktop/" + DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", DateUtils.getNowDate()) + ".xlsx";
-        log.info("配置的输出文件路径及名称是{}", reportDir);
-        // 创建 ExcelWriter 实例
+//        log.info("配置的输出文件路径及名称是{}", reportDir);
+        /*// 创建 ExcelWriter 实例
         ExcelWriter writer = EasyExcel
                 // 写入到
                 .write(reportDir)
@@ -196,7 +204,29 @@ public class BusinessController extends BaseController {
         // 结束
         writer.finish();
         writer.close();
-        return R.ok("下载成功");
+        return R.ok("下载成功");*/
+        // 使用 ByteArrayOutputStream 来捕获 Excel 生成的输出
+        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+
+        // 使用 EasyExcel 填充模板并写入到输出流中
+        EasyExcel.write(outputStream, AssayDetailRes.class)
+                .withTemplate(reportTemplateFile)
+//                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 可选:自动调整列宽
+                .sheet("Sheet1")
+                .doFill(list);
+
+        // 转换 ByteArrayOutputStream 到 ByteArrayInputStream
+        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
+
+        // 设置 HTTP 响应头
+        HttpHeaders headers = new HttpHeaders();
+        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode("化验记录") + ".xlsx");
+        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
+
+        // 返回 ResponseEntity
+        return ResponseEntity.ok()
+                .headers(headers)
+                .body(new InputStreamResource(inputStream));
     }
 
 
@@ -218,9 +248,8 @@ public class BusinessController extends BaseController {
      * 接口7:导出 通过日期获取的化验室质控样的报表统计信息到Excel
      * @param response
      */
-//    @PostMapping("/exportAssayPageListByDeviceNoAndDate")
     @GetMapping("/exportAssayCountListByDates")
-    public R<String> exportAssayCountListByDates(HttpServletResponse response, AssayReq assayReq)
+    public ResponseEntity<InputStreamResource> exportAssayCountListByDates(HttpServletResponse response, AssayReq assayReq)
     {
         log.info("进入了 导出 通过日期获取的化验室质控样的报表统计信息到Excel 接口,请求参数是{}", JSON.toJSONString(assayReq));
         DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
@@ -231,7 +260,7 @@ public class BusinessController extends BaseController {
 //        String templateFilePath = "classpath:/assay-record.xlsx";
         // 输出文件路径
 //        String outFilePath = "/Users/wangmiaomiao/Desktop/" + DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", DateUtils.getNowDate()) + ".xlsx";
-        log.info("配置的输出文件路径及名称是{}", countDir);
+        /*log.info("配置的输出文件路径及名称是{}", countDir);
         // 创建 ExcelWriter 实例
         ExcelWriter writer = EasyExcel
                 // 写入到
@@ -252,7 +281,29 @@ public class BusinessController extends BaseController {
         // 结束
         writer.finish();
         writer.close();
-        return R.ok("下载成功");
+        return R.ok("下载成功");*/
+        // 使用 ByteArrayOutputStream 来捕获 Excel 生成的输出
+        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+
+        // 使用 EasyExcel 填充模板并写入到输出流中
+        EasyExcel.write(outputStream, AssayQualityDetailRes.class)
+                .withTemplate(countTemplateFile)
+//                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 可选:自动调整列宽
+                .sheet("Sheet1")
+                .doFill(list);
+
+        // 转换 ByteArrayOutputStream 到 ByteArrayInputStream
+        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
+
+        // 设置 HTTP 响应头
+        HttpHeaders headers = new HttpHeaders();
+        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode("实验室报表") + ".xlsx");
+        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
+
+        // 返回 ResponseEntity
+        return ResponseEntity.ok()
+                .headers(headers)
+                .body(new InputStreamResource(inputStream));
     }
 
 
@@ -274,9 +325,8 @@ public class BusinessController extends BaseController {
      * 接口9:导出 通过日期范围加水厂(可选)获取连续监测的报表统计信息到Excel
      * @param response
      */
-//    @PostMapping("/exportAssayPageListByDeviceNoAndDate")
     @GetMapping("/exportContinuousAssayCountByDates")
-    public void exportContinuousAssayCountByDates(HttpServletResponse response, AssayReq assayReq)
+    public ResponseEntity<InputStreamResource> exportContinuousAssayCountByDates(HttpServletResponse response, AssayReq assayReq)
     {
         log.info("进入了 导出 通过日期范围加水厂(可选)获取连续监测的报表统计信息到Excel 接口,请求参数是{}", JSON.toJSONString(assayReq));
         DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
@@ -365,12 +415,12 @@ public class BusinessController extends BaseController {
 //        log.info("动态Excel的表头是{}", JSON.toJSONString(headers));
         log.info("动态Excel的数据列表是{}", JSON.toJSONString(dates));
 
-        EasyExcel.write(continuousCountDir)
+        /*EasyExcel.write(continuousCountDir)
                 // 动态头
                 .head(headers)
                 .sheet()
                 // 表格数据
-                .doWrite(dates);
+                .doWrite(dates);*/
 
         //测试动态生成表头 单元格合并
         /*EasyExcel.write(continuousCountDir)
@@ -380,6 +430,31 @@ public class BusinessController extends BaseController {
                 // 表格数据
                 .doWrite(getLists());*/
 
+        // 使用 ByteArrayOutputStream 来捕获 Excel 生成的输出
+        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+
+        // 使用 EasyExcel 填充模板并写入到输出流中
+        EasyExcel.write(outputStream, Object.class)
+//                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 可选:自动调整列宽
+                // 动态头
+                .head(headers)
+                .sheet()
+                // 表格数据
+                .doWrite(dates);
+
+        // 转换 ByteArrayOutputStream 到 ByteArrayInputStream
+        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
+
+        // 设置 HTTP 响应头
+        HttpHeaders httpHeaders = new HttpHeaders();
+        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode("连续检测报表") + ".xlsx");
+        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
+
+        // 返回 ResponseEntity
+        return ResponseEntity.ok()
+                .headers(httpHeaders)
+                .body(new InputStreamResource(inputStream));
+
 
 
     }

+ 1 - 1
ruoyi-system/src/main/java/com/ruoyi/business/service/impl/BusinessServiceImpl.java

@@ -109,7 +109,7 @@ public class BusinessServiceImpl implements IBusinessService {
 
     @Override
     public List<AssayQualityDetailRes> assayCountListByDates(AssayReq assayReq) {
-        List<ZAssayResult> zAssayResults = this.zAssayResultMapper.selectZAssayResultList(ZAssayResult.builder().timeBegin(assayReq.getTimeBegin()).timeEnd(assayReq.getTimeEnd()).assayType("3").build());
+        List<ZAssayResult> zAssayResults = this.zAssayResultMapper.selectZAssayResultList(ZAssayResult.builder().deviceNo(assayReq.getDeviceNo()).timeBegin(assayReq.getTimeBegin()).timeEnd(assayReq.getTimeEnd()).assayType("3").build());
         if(CollectionUtils.isEmpty(zAssayResults)){
             return Collections.emptyList();
         }