Browse Source

添加数据查询导出功能

zhoupeng 1 year ago
parent
commit
de3757bf36

+ 94 - 8
industry-admin/src/views/source/dataQuery/index.vue

@@ -75,7 +75,7 @@
                                 @click="queryData">查询</el-button>
                             <el-button ref="btn" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                             <el-button type="primary" plain icon="el-icon-folder-opened" size="mini"
-                                @click="exportData">导出</el-button>
+                                @click="exportItemListData">导出</el-button>
                         </el-form-item>
                     </el-row>
                 </el-form>
@@ -95,9 +95,15 @@
 import { showLoading } from '@/utils/cqcy'
 import { parseTime } from "@/utils/index";
 import ChooseItem from './chooseItem.vue'
-import { getItemListValue } from '@/api/source/itemGroup'
+import { getItemListValue, exportItemListData } from '@/api/source/itemGroup'
 import qs from 'qs'
 import echarts from 'echarts'
+import axios from 'axios'
+import { getToken } from '@/utils/auth'
+axios.defaults.headers['Authorization'] = 'Bearer ' + getToken()
+axios.defaults.headers['token'] = getToken()
+axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
+axios.defaults.baseURL = process.env.VUE_APP_BASE_API
 
 export default {
     created() {
@@ -239,7 +245,7 @@ export default {
                     start: 0,
                     end: 100,
                     //缩小最小值1%比例
-                    minSpan: 1
+                    // minSpan: 1
                 },
                 {
                     type: 'inside',
@@ -249,6 +255,10 @@ export default {
             //x轴
             xAxis: {
                 type: 'category',
+                // type: 'time',
+                // splitLine: {
+                //     show: false
+                // },
                 boundaryGap: false,
                 axisLine: {
                     lineStyle: {
@@ -416,8 +426,7 @@ export default {
                     let a = data[n]
                     legendData.push(a.describe ? a.describe : a.itemReadName)
                     let b = {
-                        name: a.unit ? ((a.describe ? a.describe : a.itemReadName) + '(' + a.unit + ')') :
-                            (a.describe ? a.describe : a.itemReadName),
+                        name: a.describe ? a.describe : a.itemReadName,
                         type: 'line',
                         smooth: true,
                         symbol: 'circle',
@@ -447,7 +456,7 @@ export default {
                     seriesData.push(b)
                 }
                 let decimalPlaces = parseInt(this.chartForm.decimalPlaces)
-                this.tooltip.formatter = function (params, ticket, callback) {
+                this.tooltip.formatter = function (params) {
                     let b = '<div style="display:inline;">'
                     for (let a of params) {
                         b += '<div><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:' + a.color + ';"></span><span style="color:' + a.color + '">'
@@ -584,8 +593,85 @@ export default {
             })
         },
         /** 导出统计图数据 */
-        exportData() {
-            console.log("---导出统计图-----")
+        exportItemListData() {
+            if (this.chartForm.idList.length == 0) {
+                this.$message({
+                    message: '请选择数据项',
+                    type: 'warning'
+                })
+                return
+            }
+            let startTime;
+            let endTime;
+            if (this.chartForm.trendType == 0) {
+                if (!this.chartForm.frequencyValue) {
+                    this.$message({
+                        message: '频率不能为空',
+                        type: 'warning'
+                    })
+                    return
+                }
+                if (!this.chartForm.timeValue) {
+                    this.$message({
+                        message: '时间长度不能为空',
+                        type: 'warning'
+                    })
+                    return
+                }
+
+                let currentTime = new Date().getTime()
+                let count = this.timeCalculation(this.chartForm.timeValue, this.chartForm.timeType)
+                startTime = parseTime(new Date(currentTime - count))
+                endTime = parseTime(currentTime)
+                //如果为历史趋势
+            } else if (this.chartForm.trendType == 1) {
+                if (!this.chartForm.startTime) {
+                    this.$message({
+                        message: '请选择开始时间',
+                        type: 'warning'
+                    })
+                    return
+                }
+                if (!this.chartForm.endTime) {
+                    this.$message({
+                        message: '请选择结束时间',
+                        type: 'warning'
+                    })
+                    return
+                }
+                startTime = this.chartForm.startTime
+                endTime = this.chartForm.endTime
+            }
+            let param = {
+                itemGroupId: this.chartForm.itemGroupId,
+                idList: this.chartForm.idList,
+                startTime: startTime,
+                endTime: endTime
+            }
+            let params = qs.stringify(param, { arrayFormat: 'repeat' })
+            axios({
+                method: 'get',
+                url: '/itemGroup/exportItemListData?' + params,
+                responseType: 'blob'
+            }).then((res) => {
+                // 文件流
+                const blob = new Blob([res.data])
+                let url = window.URL.createObjectURL(blob)
+                let link = document.createElement("a")
+                link.style.display = "none"
+                link.href = url
+
+                // 取后端给前端返的请求头中的文件名称
+                const fileName = res.headers["content-disposition"].split(";")[1].split("filename=")[1];
+
+                link.download = fileName
+                document.body.appendChild(link);
+                link.click();
+                document.body.removeChild(link); //下载完成移除元素
+                window.URL.revokeObjectURL(url); //释放掉blob对象
+            }, (error) => {
+                return Promise.reject(error)
+            })
         }
     },
     destroyed: function () {

+ 2 - 0
industry-system/industry-da/src/main/java/com/example/opc_da/config/InterceptorConfig.java

@@ -42,6 +42,8 @@ public class InterceptorConfig implements WebMvcConfigurer {
                 .excludePathPatterns("/influxdb/saveInFluxDBInfo")
                 .excludePathPatterns("/itemGroup/uploadModBusModel")
                 //针对大屏界面放行的请求
+                .excludePathPatterns("/itemGroup/getItemListLastValue")
+                .excludePathPatterns("/itemGroup/getItemListValue")
                 .excludePathPatterns("/mainRun/getMainRunPage")
                 .excludePathPatterns("/mainRun/getMainRunDataById")
                 .excludePathPatterns("/deviceRun/getDeviceRunPage")

+ 25 - 0
industry-system/industry-da/src/main/java/com/example/opc_da/controller/ItemGroupController.java

@@ -232,6 +232,17 @@ public class ItemGroupController {
     }
 
     /**
+     * 通过数据项id,获取相应的实时数据
+     *
+     * @param idList
+     * @return
+     */
+    @RequestMapping(value = "/getItemListLastValue", method = RequestMethod.GET)
+    public Result getItemListLastValue(@RequestParam List<Integer> idList) {
+        return itemGroupService.getItemListLastValue(idList);
+    }
+
+    /**
      * 通过数据项id,开始结束时间获取相应的数据
      *
      * @param idList
@@ -246,6 +257,20 @@ public class ItemGroupController {
     }
 
     /**
+     * 通过数据项id,开始结束时间获取相应的数据,并导出
+     *
+     * @param idList
+     * @param startTime
+     * @param endTime
+     * @return
+     */
+    @RequestMapping(value = "/exportItemListData", method = RequestMethod.GET)
+    public void exportItemListData(@RequestParam List<Integer> idList, @RequestParam String startTime,
+                                   @RequestParam String endTime, HttpServletResponse response) {
+        itemGroupService.exportItemListData(idList, startTime, endTime, response);
+    }
+
+    /**
      * 下载modbus导入模板
      */
     @GetMapping("uploadModBusModel")

+ 6 - 0
industry-system/industry-da/src/main/java/com/example/opc_da/service/ItemGroupService.java

@@ -4,6 +4,7 @@ import com.example.opc_common.entity.Item;
 import com.example.opc_common.entity.ItemGroup;
 import com.example.opc_common.util.Result;
 
+import javax.servlet.http.HttpServletResponse;
 import java.util.List;
 
 public interface ItemGroupService {
@@ -33,5 +34,10 @@ public interface ItemGroupService {
 
     Result getAllItemGroups();
 
+    Result getItemListLastValue(List<Integer> idList);
+
     Result getItemListValue(List<Integer> idList, String startTime, String endTime);
+
+    void exportItemListData(List<Integer> idList, String startTime, String endTime, HttpServletResponse response);
+
 }

+ 61 - 1
industry-system/industry-da/src/main/java/com/example/opc_da/service/impl/ItemGroupServiceImpl.java

@@ -1,5 +1,9 @@
 package com.example.opc_da.service.impl;
 
+import cn.hutool.core.collection.CollUtil;
+import cn.hutool.core.io.IoUtil;
+import cn.hutool.poi.excel.ExcelUtil;
+import cn.hutool.poi.excel.ExcelWriter;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
 import com.example.opc_common.entity.*;
@@ -19,7 +23,11 @@ import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.web.client.RestTemplate;
 
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
 import java.math.BigDecimal;
+import java.net.URLEncoder;
 import java.util.*;
 
 @Service
@@ -203,7 +211,7 @@ public class ItemGroupServiceImpl implements ItemGroupService {
         allItemList = (List<Item>) queryServiceUtil.exchangeData(allItemList);
         for (Item item : allItemList) {
             String dataValue = item.getDataValue();
-            if(Blank.isNotEmpty(dataValue)){
+            if (Blank.isNotEmpty(dataValue)) {
                 Integer itemId = item.getId();
                 DataModel dm = dmMap.get(itemId);
                 if (Blank.isNotEmpty(dm) && dm.getModelType().equals(ConstantStr.VALUE_REPLACE)) {
@@ -394,6 +402,14 @@ public class ItemGroupServiceImpl implements ItemGroupService {
     }
 
     @Override
+    public Result getItemListLastValue(List<Integer> idList) {
+        List<Item> itemList = itemGroupDao.getItemsParentByIdList(idList);
+        //从工具类中组装对应数据项的数据到集合中
+        itemList = (List<Item>) queryServiceUtil.exchangeData(itemList);
+        return Result.ok(itemList);
+    }
+
+    @Override
     public Result getItemListValue(List<Integer> idList, String startTime, String endTime) {
         List<Item> itemList = itemGroupDao.getItemsParentByIdList(idList);
         //从工具类中组装对应数据项的数据到集合中
@@ -404,4 +420,48 @@ public class ItemGroupServiceImpl implements ItemGroupService {
         );
         return Result.ok(itemList);
     }
+
+    @Override
+    public void exportItemListData(List<Integer> idList, String startTime, String endTime, HttpServletResponse response) {
+        List<Item> itemList = itemGroupDao.getItemsParentByIdList(idList);
+        //从工具类中组装对应数据项的数据到集合中
+        itemList = (List<Item>) queryServiceUtil.exchangeDatas(
+                DateUtil.strYmdhmsChangeDate(startTime),
+                DateUtil.strYmdhmsChangeDate(endTime),
+                itemList
+        );
+        List<List<String>> rows = new ArrayList<>();
+        List<String> header = CollUtil.newArrayList("时间", "数据项名称", "值");
+        rows.add(header);
+        if (Blank.isNotEmpty(itemList)) {
+            for (Item item : itemList) {
+                List<String> dataTimeList = item.getDataTimeList();
+                List<String> dataValueList = item.getDataValueList();
+                if (Blank.isNotEmpty(dataTimeList)) {
+                    for (int i = 0; i < dataTimeList.size() - 1; i++) {
+                        List<String> row = CollUtil.newArrayList(dataTimeList.get(i), item.getItemReadName(), dataValueList.get(i));
+                        rows.add(row);
+                    }
+                }
+            }
+        }
+        ServletOutputStream out = null;
+        ExcelWriter writer = null;
+        try {
+            writer = ExcelUtil.getWriter(true);
+            writer.write(rows, true);
+            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
+            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(new Date().getTime() + ".xlsx", "UTF-8"));
+            response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
+            out = response.getOutputStream();
+            writer.flush(out, true);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        } finally {
+            if (writer != null) {
+                writer.close();
+            }
+            IoUtil.close(out);
+        }
+    }
 }

+ 2 - 2
industry-system/industry-da/src/main/resources/application-dev.yml

@@ -11,9 +11,9 @@ spring:
       max-request-size: 500MB
   datasource:
     driver-class-name: com.mysql.cj.jdbc.Driver
-    url: jdbc:mysql://localhost:3306/in_data_db?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT%2B8
+    url: jdbc:mysql://192.168.1.253:3306/in_data_db?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT%2B8
     username: root
-    password: root
+    password: jd@2021
     hikari:
       # 设置是否自动提交事务,默认为true
       auto-commit: true

File diff suppressed because it is too large
+ 1 - 1
industry-system/industry-da/src/main/resources/static/page/index.html


File diff suppressed because it is too large
+ 0 - 0
industry-system/industry-da/src/main/resources/static/page/static/js/app.cc44a720.js


File diff suppressed because it is too large
+ 0 - 0
industry-system/industry-da/src/main/resources/static/page/static/js/chunk-7c94232f.6dd9a61c.js


File diff suppressed because it is too large
+ 0 - 0
industry-system/industry-da/src/main/resources/static/page/static/js/chunk-977d7f52.117587e2.js


Some files were not shown because too many files changed in this diff