Browse Source

渲染对象到excel

Raod 4 years ago
parent
commit
37ae1e796a

+ 3 - 0
report-core/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/dto/DataSetDto.java

@@ -55,4 +55,7 @@ public class DataSetDto extends GaeaBaseDTO implements Serializable {
 
 
     private Set<String> setParamList;
     private Set<String> setParamList;
 
 
+    /**指定字段*/
+    private String fieldLabel;
+
 }
 }

+ 117 - 3
report-core/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/service/impl/ReportExcelServiceImpl.java

@@ -1,17 +1,24 @@
 package com.anjiplus.template.gaea.business.modules.reportexcel.service.impl;
 package com.anjiplus.template.gaea.business.modules.reportexcel.service.impl;
 
 
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
 import com.anji.plus.gaea.constant.BaseOperationEnum;
 import com.anji.plus.gaea.constant.BaseOperationEnum;
 import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
 import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
 import com.anji.plus.gaea.exception.BusinessException;
 import com.anji.plus.gaea.exception.BusinessException;
 import com.anji.plus.gaea.utils.GaeaAssert;
 import com.anji.plus.gaea.utils.GaeaAssert;
 import com.anji.plus.gaea.utils.GaeaBeanUtils;
 import com.anji.plus.gaea.utils.GaeaBeanUtils;
 import com.anjiplus.template.gaea.business.code.ResponseCode;
 import com.anjiplus.template.gaea.business.code.ResponseCode;
+import com.anjiplus.template.gaea.business.modules.dataset.controller.dto.DataSetDto;
+import com.anjiplus.template.gaea.business.modules.dataset.controller.dto.OriginalDataDto;
+import com.anjiplus.template.gaea.business.modules.dataset.service.DataSetService;
 import com.anjiplus.template.gaea.business.modules.report.dao.ReportMapper;
 import com.anjiplus.template.gaea.business.modules.report.dao.ReportMapper;
 import com.anjiplus.template.gaea.business.modules.report.dao.entity.Report;
 import com.anjiplus.template.gaea.business.modules.report.dao.entity.Report;
 import com.anjiplus.template.gaea.business.modules.reportexcel.controller.dto.ReportExcelDto;
 import com.anjiplus.template.gaea.business.modules.reportexcel.controller.dto.ReportExcelDto;
 import com.anjiplus.template.gaea.business.modules.reportexcel.dao.ReportExcelMapper;
 import com.anjiplus.template.gaea.business.modules.reportexcel.dao.ReportExcelMapper;
 import com.anjiplus.template.gaea.business.modules.reportexcel.dao.entity.ReportExcel;
 import com.anjiplus.template.gaea.business.modules.reportexcel.dao.entity.ReportExcel;
 import com.anjiplus.template.gaea.business.modules.reportexcel.service.ReportExcelService;
 import com.anjiplus.template.gaea.business.modules.reportexcel.service.ReportExcelService;
+import com.anjiplus.template.gaea.business.modules.reportexcel.util.XlsSheetUtil;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.Logger;
@@ -20,6 +27,8 @@ import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
 
 
+import java.util.List;
+
 /**
 /**
  * TODO
  * TODO
  *
  *
@@ -34,6 +43,9 @@ public class ReportExcelServiceImpl implements ReportExcelService {
     @Autowired
     @Autowired
     private ReportExcelMapper reportExcelMapper;
     private ReportExcelMapper reportExcelMapper;
 
 
+    @Autowired
+    private DataSetService dataSetService;
+
 
 
     @Autowired
     @Autowired
     private ReportMapper reportMapper;
     private ReportMapper reportMapper;
@@ -93,9 +105,9 @@ public class ReportExcelServiceImpl implements ReportExcelService {
             reportExcelDto.setSetParam(setParam);
             reportExcelDto.setSetParam(setParam);
         }
         }
         reportExcelDto.setReportName(report.getReportName());
         reportExcelDto.setReportName(report.getReportName());
-        // TODO 数据集解析,待扩展
-//        JSONObject jsonObject = reportUtil.reportParse(reportExcelDto);
-//        reportExcelDto.setJsonStr(JSONObject.toJSONString(jsonObject));
+        // 数据集解析
+        String jsonStr = analysisReportData(reportExcelDto);
+        reportExcelDto.setJsonStr(jsonStr);
 //        reportExcelDto.setTotal(jsonObject.getJSONObject("rows").size());
 //        reportExcelDto.setTotal(jsonObject.getJSONObject("rows").size());
         return reportExcelDto;
         return reportExcelDto;
     }
     }
@@ -106,4 +118,106 @@ public class ReportExcelServiceImpl implements ReportExcelService {
         return true;
         return true;
     }
     }
 
 
+    /**
+     * 解析报表数据,动态插入列表数据和对象数据
+     */
+    private String analysisReportData(ReportExcelDto reportExcelDto) {
+
+        String jsonStr = reportExcelDto.getJsonStr();
+        List<JSONObject> dbObjectList = (List<JSONObject>) JSON.parse(jsonStr);
+
+        if (dbObjectList != null && dbObjectList.size() > 0) {
+            for (int x = 0; x < dbObjectList.size(); x++) {
+                analysisSheet(dbObjectList.get(x));
+            }
+        }
+
+        return JSONObject.toJSONString(dbObjectList);
+    }
+
+    /**
+     * 解析单sheet
+     *
+     * @param dbObject
+     */
+    private void analysisSheet(JSONObject dbObject) {
+        //data是一个二维数组
+        if (dbObject.containsKey("data") && null != dbObject.get("data")) {
+            List<JSONArray> data = (List<JSONArray>) dbObject.get("data");
+
+
+            //行
+            for (int r = 0; r < data.size(); r++) {
+                JSONArray jsonArray = data.get(r);
+                //列
+                for (int c = 0; c < jsonArray.size(); c++) {
+                    //单元格
+                    JSONObject cell = jsonArray.getJSONObject(c);
+                    if (null != cell && cell.containsKey("v") && StringUtils.isNotBlank(cell.getString("v"))) {
+                        String v = cell.getString("v");
+                        DataSetDto dataSet = getDataSet(v);
+                        if (null != dataSet) {
+                            OriginalDataDto originalDataDto = dataSetService.getData(dataSet);
+                            if (null != originalDataDto.getData()) {
+                                if (originalDataDto.getData().size() == 1) {
+                                    //对象
+                                    JSONObject jsonObject = originalDataDto.getData().get(0);
+                                    String fieldLabel = jsonObject.getString(dataSet.getFieldLabel());
+
+                                    String replace = v.replace("#{".concat(dataSet.getSetCode()).concat(".").concat(dataSet.getFieldLabel()).concat("}"), fieldLabel);
+                                    dbObject.getJSONArray("data").getJSONArray(r).getJSONObject(c).put("v", replace);
+                                    dbObject.getJSONArray("data").getJSONArray(r).getJSONObject(c).put("m", replace);
+
+                                } else {
+                                    //集合
+                                    JSONObject jsonObject = originalDataDto.getData().get(0);
+                                    String fieldLabel = jsonObject.getString(dataSet.getFieldLabel());
+
+                                    String replace = v.replace("#{".concat(dataSet.getSetCode()).concat(".").concat(dataSet.getFieldLabel()).concat("}"), fieldLabel);
+                                    dbObject.getJSONArray("data").getJSONArray(r).getJSONObject(c).put("v", replace);
+                                    dbObject.getJSONArray("data").getJSONArray(r).getJSONObject(c).put("m", replace);
+                                }
+                            }
+
+                        }
+                    }
+
+
+
+                }
+            }
+
+
+            System.out.println("aaaa");
+
+
+        }
+
+
+    }
+
+
+    /**
+     * 解析 #{xxxx.xxxxx} 数据
+     * @param v
+     * @return
+     */
+    private DataSetDto getDataSet(String v) {
+        DataSetDto dto = new DataSetDto();
+        if (v.contains("#{") && v.contains("}")) {
+            int start = v.indexOf("#{") + 2;
+            int end = v.indexOf("}");
+            if (start < end) {
+                String substring = v.substring(start, end);
+                if (substring.contains(".")) {
+                    String[] split = substring.split("\\.");
+                    dto.setSetCode( split[0]);
+                    dto.setFieldLabel(split[1]);
+                    return dto;
+                }
+            }
+        }
+        return null;
+    }
+
 }
 }

+ 15 - 0
report-core/src/test/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/XlsSheetUtilTest.java

@@ -8,6 +8,7 @@ import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.OutputStream;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.List;
 
 
 
 
@@ -36,4 +37,18 @@ public class XlsSheetUtilTest {
         System.out.println("start");
         System.out.println("start");
     }
     }
 
 
+
+    @Test
+    public void test2(){
+        List<String> list = new LinkedList<>();
+        list.add("a");
+        list.add("b");
+        list.add("c");
+        list.add("d");
+        list.add("e");
+        list.add(2, "f");
+        //CopyOnWriteArrayList
+        System.out.println(list);
+    }
+
 }
 }

+ 1 - 3
report-ui/src/views/report/excelreport/designer/index.vue

@@ -67,8 +67,6 @@
           </el-button>
           </el-button>
         </el-tooltip>
         </el-tooltip>
       </div>
       </div>
-      <!-- <div id="x-spreadsheet-demo"
-           class="excel-designer" /> -->
       <div id="luckysheet"
       <div id="luckysheet"
            style="margin:0px;padding:0px;position:absolute;width:100%;height:95vh;left: 0px;top: 30px;bottom:0px;" />
            style="margin:0px;padding:0px;position:absolute;width:100%;height:95vh;left: 0px;top: 30px;bottom:0px;" />
       <div id="qrCode"
       <div id="qrCode"
@@ -493,7 +491,7 @@ export default {
       }
       }
     },
     },
     async preview () {
     async preview () {
-      var routeUrl = this.$router.resolve({ path: '/report/excelreport/viewer', query: { reportCode: this.reportCode } })
+      var routeUrl = this.$router.resolve({ path: '/excelreport/viewer', query: { reportCode: this.reportCode } })
       window.open(routeUrl.href, '_blank')
       window.open(routeUrl.href, '_blank')
     },
     },
     async queryAllDataSet () {
     async queryAllDataSet () {

+ 57 - 83
report-ui/src/views/report/excelreport/viewer/index.vue

@@ -44,8 +44,8 @@
       </div>
       </div>
     </div>
     </div>
     <div class="layout-middle">
     <div class="layout-middle">
-      <div id="x-spreadsheet-demo"
-           class="excel-designer" />
+      <div id="luckysheet"
+           style="margin:0px;padding:0px;position:absolute;width:100%;height:95vh;left: 0px;top: 30px;bottom:0px;" />
     </div>
     </div>
   </div>
   </div>
 </template>
 </template>
@@ -78,43 +78,6 @@ export default {
     }
     }
   },
   },
   mounted () {
   mounted () {
-    this.options = {
-      mode: 'read', // edit | read
-      showToolbar: false,
-      showGrid: true,
-      showContextmenu: false,
-      view: {
-        height: () => document.documentElement.clientHeight,
-        width: () => document.getElementsByClassName('layout-middle')[0].clientWidth,
-      },
-      row: {
-        len: 100,
-        height: 25,
-      },
-      col: {
-        len: 52,
-        width: 100,
-        indexWidth: 60,
-        minWidth: 60,
-      },
-      style: {
-        bgcolor: '#ffffff',
-        align: 'left',
-        valign: 'middle',
-        textwrap: false,
-        strike: false,
-        underline: false,
-        color: '#0a0a0a',
-        font: {
-          name: 'Helvetica',
-          size: 10,
-          bold: false,
-          italic: false,
-        },
-      },
-    }
-    // this.sheet = new Spreadsheet('#x-spreadsheet-demo', this.options).loadData({})
-    this.load()
     this.preview()
     this.preview()
   },
   },
   created () {
   created () {
@@ -126,8 +89,6 @@ export default {
       this.params.setParam = JSON.stringify(arr)
       this.params.setParam = JSON.stringify(arr)
       const { code, data } = await preview(this.params)
       const { code, data } = await preview(this.params)
       if (code !== '200') return
       if (code !== '200') return
-      this.excelData = JSON.parse(data.jsonStr)
-      this.sheet.loadData(this.excelData)
     },
     },
     async preview () {
     async preview () {
       this.excelData = {}
       this.excelData = {}
@@ -149,7 +110,8 @@ export default {
       this.tableData2 = extendArry
       this.tableData2 = extendArry
 
 
       this.excelData = data.jsonStr
       this.excelData = data.jsonStr
-      this.sheet.loadData(JSON.parse(this.excelData))
+      this.sheetData = (data == null ? [{}] : JSON.parse(data.jsonStr))
+      this.createSheet();
     },
     },
     download (val) {
     download (val) {
       const result = {}
       const result = {}
@@ -176,55 +138,67 @@ export default {
       }
       }
       return objSecond
       return objSecond
     },
     },
-    load () {
-      const rows10 = { len: 1000 }
-      for (let i = 0; i < 1000; i += 1) {
-        rows10[i] = {
-          cells: {},
-        }
-      }
-      const rows = {}
-      this.sheet = x_spreadsheet('#x-spreadsheet-demo', this.options)
-        .loadData([
+    //初始化表格
+    createSheet(){
+      const options = {
+        container: 'luckysheet', // 设定DOM容器的id
+        title: 'Luckysheet Demo', // 设定表格名称
+        lang: 'zh', // 设定表格语言
+        plugins:['chart'],
+        data:[
           {
           {
-            freeze: 'B3',
-            styles: [],
-            merges: [],
-            cols: {
-              len: 20,
-              // 2: { width: 200 },
+            "name": "report", //工作表名称
+            "color": "", //工作表颜色
+            "index": 0, //工作表索引
+            "status": 1, //激活状态
+            "order": 0, //工作表的下标
+            "hide": 0,//是否隐藏
+            "row": 36, //行数
+            "column": 18, //列数
+            "defaultRowHeight": 19, //自定义行高
+            "defaultColWidth": 73, //自定义列宽
+            "celldata": [], //初始化使用的单元格数据
+            "config": {
+              "merge":{}, //合并单元格
+              "rowlen":{}, //表格行高
+              "columnlen":{}, //表格列宽
+              "rowhidden":{}, //隐藏行
+              "colhidden":{}, //隐藏列
+              "borderInfo":{}, //边框
+              "authority":{}, //工作表保护
+
             },
             },
-            rows,
-          },
-          { name: 'sheet-test', rows: rows10 },
-        ])
-        .change((cdata) => {
-          const dataRect = this.sheet.data.getDataRect()
-        })
-      this.sheet
-        .on('cell-selected', (cell, ri, ci) => {
-          // console.log('cell:', cell, ', ri:', ri, ', ci:', ci);
-        })
-        .on('cell-edited', (text, ri, ci) => {
-          // console.log('text:', text, ', ri: ', ri, ', ci:', ci);
-        })
-      this.sheet.on('printSettings', () => {
-        // 打印设置.
-      })
-      this.sheet.on('generateQrcode', () => {
-        // 生成二维码.
-        console.log('insertImg', this.dialogVisible)
-      })
-      this.sheet.on('insertImg', () => {
-        // 插入图片
-      })
+            "scrollLeft": 0, //左右滚动条位置
+            "scrollTop": 315, //上下滚动条位置
+            "luckysheet_select_save": [], //选中的区域
+            "calcChain": [],//公式链
+            "isPivotTable":false,//是否数据透视表
+            "pivotTable":{},//数据透视表设置
+            "filter_select": {},//筛选范围
+            "filter": null,//筛选配置
+            "luckysheet_alternateformat_save": [], //交替颜色
+            "luckysheet_alternateformat_save_modelCustom": [], //自定义交替颜色
+            "luckysheet_conditionformat_save": {},//条件格式
+            "frozen": {}, //冻结行列配置
+            "chart": [], //图表配置
+            "zoomRatio":1, // 缩放比例
+            "image":[], //图片
+            "showGridLines": 1, //是否显示网格线
+            "dataVerification":{} //数据验证配置
+          }
+        ]
+      };
+      options.data = this.sheetData;
+
+      $(function () {
+        luckysheet.create(options);
+      });
     },
     },
   },
   },
 }
 }
 </script>
 </script>
 
 
 <style scoped lang="scss">
 <style scoped lang="scss">
-@import '../../../../components/x-spreadsheet/dist/xspreadsheet.css';
 .download {
 .download {
   width: 100%;
   width: 100%;
   float: left;
   float: left;