Explorar el Código

逆变器、风机数据导出文件名称转义编码处理

xusl hace 7 meses
padre
commit
d3c4a16f49

+ 122 - 2
cpp-admin/src/main/java/com/cpp/web/controller/stationDataQuery/InverterStatusDataController.java

@@ -1,20 +1,32 @@
 package com.cpp.web.controller.stationDataQuery;
 
+import cn.hutool.core.date.DateUtil;
 import com.baomidou.mybatisplus.core.metadata.OrderItem;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.cpp.common.core.domain.R;
-import com.cpp.web.domain.station.InverterStatusData;
+import com.cpp.web.domain.station.*;
+import com.cpp.web.service.station.ElectricFieldService;
+import com.cpp.web.service.station.InverterInfoService;
 import com.cpp.web.service.station.InverterStatusDataService;
+import com.cpp.web.service.station.WindTurbineInfoService;
+import com.cpp.web.utils.DownloadFileUrlCodeUtil;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
-import java.util.Date;
+import javax.servlet.http.HttpServletResponse;
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.text.SimpleDateFormat;
+import java.util.*;
 
 
 /**
@@ -27,9 +39,12 @@ import java.util.Date;
 @RequiredArgsConstructor
 @RequestMapping("/inverterstatusdata")
 @Api(value = "inverterstatusdata", tags = "idp_inverter_status_data管理")
+@Slf4j
 public class InverterStatusDataController {
 
     private final InverterStatusDataService inverterStatusDataService;
+    private final ElectricFieldService electricFieldService;
+    private final InverterInfoService inverterInfoService;
 
     /**
      * 分页查询
@@ -63,4 +78,109 @@ public class InverterStatusDataController {
         page.setMaxLimit((long) -1);
         return R.ok(inverterStatusDataService.page(page, inverterStatusDataService.getByStationCodeAndEquipmentIdAndTimeBetween(stationCode, equipmentId, new Date(startTime), new Date(endTime))));
     }
+
+    @GetMapping("/export")
+    public void export(String stationCode, String equipmentId, Long startTime, Long endTime, HttpServletResponse response){
+        BufferedOutputStream bos = null;
+        try {
+            ElectricField electricField = electricFieldService.findByStationCode(stationCode);
+            List<InverterInfo> inverterInfoList = inverterInfoService.findByStationCode(stationCode);
+            List<InverterStatusData> list = inverterStatusDataService.list(inverterStatusDataService.getByStationCodeAndEquipmentIdAndTimeBetween(stationCode, equipmentId, new Date(startTime), new Date(endTime)));
+            StringBuilder templateContent = new StringBuilder();
+            response.setCharacterEncoding("UTF-8");
+
+            List<String> tableColumns = new ArrayList<>();
+            tableColumns.add("所属场站");
+            tableColumns.add("设备名称");
+            tableColumns.add("时间");
+            tableColumns.add("状态");
+            tableColumns.add("有功(KW)");
+            tableColumns.add("无功(KVar)");
+            tableColumns.add("电压(V)");
+            tableColumns.add("电流(A)");
+            tableColumns.add("当日发电量(kW·h)");
+            tableColumns.add("累积发电量(MW·h)");
+            tableColumns.add("当日并网小时数");
+
+
+            String header = "";
+            StringBuilder content = new StringBuilder();
+
+            for (String tableColumn : tableColumns) {
+                header += "\"" + tableColumn + "\",";
+            }
+            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+            // 设备名称集合
+            Set<String> nameList = new TreeSet<>();
+            if (!list.isEmpty()){
+                list.sort(Comparator.comparing(InverterStatusData::getEquipmentId).thenComparing(InverterStatusData::getTime));
+            }
+            for (InverterStatusData inverterStatusData : list) {
+                content.append(electricField.getName() + "," );
+                Optional<String> name = inverterInfoList.stream()
+                        .filter(w -> w.getId().longValue()==inverterStatusData.getEquipmentId().longValue())
+                        .map(InverterInfo::getName)
+                        .findFirst();
+                content.append(name.get() + "," );
+                nameList.add(name.get());
+                content.append(DateUtil.format(inverterStatusData.getTime(),"yyyy-MM-dd HH:mm") + "," );
+                int statusValue = inverterStatusData.getStatus();
+                if (statusValue == 1) {
+                    content.append("运行,");
+                } else if (statusValue == 2) {
+                    content.append("待机,");
+                } else if (statusValue == 3) {
+                    content.append("停用,");
+                } else if (statusValue == 4) {
+                    content.append("故障,");
+                }
+                content.append(inverterStatusData.getActivePower() + "," );
+                content.append(inverterStatusData.getReactivePower() + "," );
+                content.append(inverterStatusData.getVoltage() + "," );
+                content.append(inverterStatusData.getElectricalCurrent() + "," );
+                content.append(inverterStatusData.getDayElectricQuantity() + "," );
+                content.append(inverterStatusData.getCumulativeGeneratedEnergy() + "," );
+                content.append(inverterStatusData.getDayGridConnectedHours() + "," );
+                content.append("\r\n");
+            }
+
+            header += "\r\n";
+            templateContent.append(header);
+
+            templateContent.append(content.toString());
+
+            String fileName = "";
+            String fileNameDeviceName = "";
+            for (String name : nameList) {
+                fileNameDeviceName += name + "_";
+            }
+            if (sdf.format(startTime).equals(sdf.format(endTime))) {
+                fileName = electricField.getName() + sdf.format(startTime) + "[" +fileNameDeviceName.substring(0,fileNameDeviceName.length()-1) + "].csv";
+            } else {
+                fileName = electricField.getName() + sdf.format(startTime) + "至" + sdf.format(endTime) + "[" +fileNameDeviceName.substring(0,fileNameDeviceName.length()-1) + "].csv";
+            }
+
+            response.setContentType("application/x-msdownload;charset=UTF-8");
+            response.setHeader("Content-disposition", "attachment; filename=" + DownloadFileUrlCodeUtil.transUrlChinese(fileName));
+            byte[] templateContentBytes = templateContent.toString().getBytes("UTF-8");
+            bos = new BufferedOutputStream(response.getOutputStream());
+            bos.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
+            bos.write(templateContentBytes);
+            response.flushBuffer();
+
+        } catch (Exception e) {
+            log.error("系统错误:" + e.getMessage(), e);
+            throw new RuntimeException(e);
+        } finally {
+            if (bos != null) {
+                try {
+                    bos.close();
+                } catch (IOException e) {
+                    log.error("系统错误:" + e.getMessage(), e);
+                }
+            }
+        }
+    }
+
+
 }

+ 2 - 2
cpp-admin/src/main/java/com/cpp/web/controller/stationDataQuery/WindTurbineStatusDataController.java

@@ -15,6 +15,7 @@ import com.cpp.web.dto.TableColumn;
 import com.cpp.web.service.station.ElectricFieldService;
 import com.cpp.web.service.station.WindTurbineInfoService;
 import com.cpp.web.service.station.WindTurbineStatusDataService;
+import com.cpp.web.utils.DownloadFileUrlCodeUtil;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.RequiredArgsConstructor;
@@ -160,13 +161,12 @@ public class WindTurbineStatusDataController {
             }
 
             response.setContentType("application/x-msdownload;charset=UTF-8");
-            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
+            response.setHeader("Content-disposition", "attachment; filename=" + DownloadFileUrlCodeUtil.transUrlChinese(fileName));
             byte[] templateContentBytes = templateContent.toString().getBytes("UTF-8");
             bos = new BufferedOutputStream(response.getOutputStream());
             bos.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
             bos.write(templateContentBytes);
             response.flushBuffer();
-
         } catch (Exception e) {
             log.error("系统错误:" + e.getMessage(), e);
             throw new RuntimeException(e);

+ 38 - 0
cpp-admin/src/main/java/com/cpp/web/utils/DownloadFileUrlCodeUtil.java

@@ -0,0 +1,38 @@
+package com.cpp.web.utils;
+
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+
+/**
+ * @author jy
+ * @since 2024/11/06
+ */
+@Slf4j
+public class DownloadFileUrlCodeUtil {
+    public static String transUrlChinese(String str) {
+
+        String resultURL = "";
+        try {
+            for (int i = 0; i < str.length(); i++) {
+                char charAt = str.charAt(i);
+                //只对汉字处理
+                if (isChineseChar(charAt)) {
+                    String encode = URLEncoder.encode(charAt + "", "UTF-8");
+                    resultURL += encode;
+                } else {
+                    resultURL += charAt;
+                }
+            }
+        } catch (UnsupportedEncodingException e) {
+            log.warn("解码异常!");
+        }
+        return resultURL;
+    }
+
+    private static boolean isChineseChar(char c) {
+        return String.valueOf(c).matches("[\u4e00-\u9fff\u3400-\u4dbf\u20000-\u2a6df\u2a700-\u2b73f\u2b740-\u2b81f\u2b820-\u2ceaf\uf900-\ufaff]");
+    }
+
+}

+ 37 - 4
cpp-ui/src/views/stationDataQuery/inverterstatusdata/index.vue

@@ -37,6 +37,8 @@
         <el-form-item>
           <el-button type="primary" style="margin-left: 5px" icon="el-icon-search" @click="beforeQuery">查询
           </el-button>
+          <el-button type="primary" style="margin-left: 5px" icon="el-icon-download" @click="exportFile">导出
+          </el-button>
         </el-form-item>
       </el-form>
     </div>
@@ -124,7 +126,7 @@ export default {
     this.$axios.get('/inverterinfo/findAll').then((res) => {
       this.nameList = res.data
       if (res.data.length > 0) {
-        // 默认选中前5个风机
+        // 默认选中前5个逆变器
         let count = 0
         for (let i = 0; i < res.data.length; i++) {
           if (count <= 4) {
@@ -133,18 +135,45 @@ export default {
           }
         }
       }
-      // 获取场站下拉列表
-      this.getStationCode()
     }).catch((error) => {
       this.$message.error('获取逆变器转义名称出错' + error)
     })
 
   },
   mounted() {
-
+    // 获取场站下拉列表
+    this.getStationCode()
   },
   computed: {},
   methods: {
+    exportFile() {
+      if (this.equipmentId.length == 0) {
+        this.$message.error("请选择逆变器设备查询")
+        return
+      }
+      let startTime = Math.round(this.dateTime[0])
+      let endTime = Math.round(this.dateTime[1])
+      if (endTime <= startTime) {
+        this.$message.error("开始时间不能大于结束时间")
+        return
+      }
+
+      this.loading = true
+      let queryParams = {
+        "stationCode": this.stationCode,
+        "equipmentId": this.equipmentId.join(','),
+        "startTime": startTime,
+        "endTime": endTime,
+      }
+      this.$axios.get('/inverterstatusdata/export', {
+        params: queryParams,
+        responseType: 'blob',// 用于解决中文乱码
+      }).then(response => {
+        this.loading = false
+      }).catch(() => {
+        this.loading = false
+      })
+    },
     beforeQuery(){
       this.currentPage = 1
       this.pageSize = 10
@@ -189,6 +218,10 @@ export default {
       this.dataQuery();
     },
     dataQuery() {
+      if (this.equipmentId.length == 0) {
+        this.$message.error("请选择逆变器设备查询")
+        return
+      }
       let startTime = Math.round(this.dateTime[0])
       let endTime = Math.round(this.dateTime[1])
       if (endTime <= startTime) {