chenw 6 жил өмнө
parent
commit
2058d64757

+ 5 - 0
bi-server/pom.xml

@@ -45,6 +45,11 @@
       <artifactId>java-jwt</artifactId>
     </dependency>
 
+    <dependency>
+      <groupId>org.apache.poi</groupId>
+      <artifactId>poi</artifactId>
+    </dependency>
+
     <!--<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-tomcat</artifactId>

+ 18 - 1
bi-server/src/main/java/com/usoftchina/bi/server/controller/dashboard/DashboardsController.java

@@ -7,6 +7,7 @@ import com.usoftchina.bi.core.utils.EncryUtil;
 import com.usoftchina.bi.server.model.bo.ShareReqBO;
 import com.usoftchina.bi.server.model.pojo.annotation.CheckToken;
 import com.usoftchina.bi.server.model.pojo.annotation.Log;
+import com.usoftchina.bi.server.model.vo.dataVo.DashboardExportInfo;
 import com.usoftchina.bi.server.model.vo.configVo.ChangeOrderInfo;
 import com.usoftchina.bi.server.model.vo.configVo.ChartsToDashInfo;
 import com.usoftchina.bi.server.model.vo.configVo.DashboardsInfo;
@@ -15,11 +16,15 @@ import com.usoftchina.bi.server.service.dashboard.DashboardsService;
 import com.usoftchina.bi.server.service.dashboard.DashboardsToChartsUtilService;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.URLEncoder;
 import java.sql.SQLException;
-import java.util.List;
 
 @RestController
 @Api(description = "看板相关接口")
@@ -165,4 +170,16 @@ public class DashboardsController {
     public RepEntity copy(@RequestHeader String token, @RequestBody DashboardCopyInfo dashboardCopyInfo){
         return dashboardsService.copy(token, dashboardCopyInfo);
     }
+
+    @ApiOperation(value = "导出", notes = "导出")
+    @CheckToken
+    @PostMapping("/dashboard/export")
+    public void export(@RequestHeader String token, @RequestBody DashboardExportInfo dashboardExportInfo,  HttpServletResponse response) throws IOException {
+        HSSFWorkbook workbook = dashboardsService.export(dashboardExportInfo);
+        response.setContentType("application/vnd.ms-excel");
+        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(dashboardExportInfo.getDashboardName() + ".xlsx", "UTF-8"));
+        OutputStream out = response.getOutputStream();
+        workbook.write(out);
+        out.close();
+    }
 }

+ 3 - 0
bi-server/src/main/java/com/usoftchina/bi/server/dao/dataSource/DataConnectorMapper.java

@@ -385,4 +385,7 @@ public interface DataConnectorMapper {
     @Select("select table_name from bi_data_connectors where id = #{id}")
     String getSqlByid(int id);
 
+    @Select("SELECT * FROM (${table}) ${condition}")
+    List<Map<String, Object>> getExportData(@Param("table") String table, @Param("condition") String condition);
+
 }

+ 47 - 0
bi-server/src/main/java/com/usoftchina/bi/server/model/vo/dataVo/DashboardExportInfo.java

@@ -0,0 +1,47 @@
+package com.usoftchina.bi.server.model.vo.dataVo;
+
+import java.util.List;
+
+/**
+ * @Author chenwei
+ * @Date 2019-06-12
+ */
+public class DashboardExportInfo {
+
+    /**
+     * 报表ID
+     */
+    private int dashboardId;
+    /**
+     * 数据源信息
+     */
+    private List<DataSourceExportInfo> data;
+    /**
+     * 报表名称
+     */
+    private String dashboardName;
+
+    public int getDashboardId() {
+        return dashboardId;
+    }
+
+    public void setDashboardId(int dashboardId) {
+        this.dashboardId = dashboardId;
+    }
+
+    public List<DataSourceExportInfo> getData() {
+        return data;
+    }
+
+    public void setData(List<DataSourceExportInfo> data) {
+        this.data = data;
+    }
+
+    public String getDashboardName() {
+        return dashboardName;
+    }
+
+    public void setDashboardName(String dashboardName) {
+        this.dashboardName = dashboardName;
+    }
+}

+ 33 - 0
bi-server/src/main/java/com/usoftchina/bi/server/model/vo/dataVo/DataSourceExportInfo.java

@@ -0,0 +1,33 @@
+package com.usoftchina.bi.server.model.vo.dataVo;
+
+import com.usoftchina.bi.server.model.bo.Screen;
+
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * @Author chenwei
+ * @Date 2019-06-12
+ */
+public class DataSourceExportInfo implements Serializable {
+
+    private int dataSourceId;
+
+    private List<Screen> filter;
+
+    public int getDataSourceId() {
+        return dataSourceId;
+    }
+
+    public void setDataSourceId(int dataSourceId) {
+        this.dataSourceId = dataSourceId;
+    }
+
+    public List<Screen> getFilter() {
+        return filter;
+    }
+
+    public void setFilter(List<Screen> filter) {
+        this.filter = filter;
+    }
+}

+ 212 - 3
bi-server/src/main/java/com/usoftchina/bi/server/service/dashboard/DashboardsService.java

@@ -3,27 +3,36 @@ package com.usoftchina.bi.server.service.dashboard;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
+import com.fasterxml.jackson.databind.type.CollectionType;
 import com.usoftchina.bi.core.base.*;
 import com.usoftchina.bi.core.exception.MyException;
+import com.usoftchina.bi.core.utils.CollectionUtils;
 import com.usoftchina.bi.core.utils.EncryUtil;
 import com.usoftchina.bi.server.dao.chart.ChartsConfigMapper;
 import com.usoftchina.bi.server.dao.dashboard.DashboardsMapper;
+import com.usoftchina.bi.server.dao.dataSource.DataConnectorMapper;
 import com.usoftchina.bi.server.dao.user.UserMapper;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.github.pagehelper.PageInfo;
 import com.usoftchina.bi.server.model.bo.DashOrder;
+import com.usoftchina.bi.server.model.bo.Screen;
 import com.usoftchina.bi.server.model.bo.ShareReqBO;
 import com.usoftchina.bi.server.model.po.ChartConfig;
 import com.usoftchina.bi.server.model.po.Dashboards;
+import com.usoftchina.bi.server.model.po.DataConnector;
 import com.usoftchina.bi.server.model.vo.configVo.ChangeOrderInfo;
+import com.usoftchina.bi.server.model.vo.configVo.ColumnRenameInfo;
 import com.usoftchina.bi.server.model.vo.configVo.DashboardsInfo;
-import com.usoftchina.bi.server.model.vo.dataVo.DashboardCopyInfo;
-import com.usoftchina.bi.server.model.vo.dataVo.DashboardOrderInfo;
-import com.usoftchina.bi.server.model.vo.dataVo.DataSourceCopyInfo;
+import com.usoftchina.bi.server.model.vo.dataVo.*;
 import com.usoftchina.bi.server.service.chart.ChartsUtilService;
 import com.usoftchina.bi.core.utils.GetTokenDataUtil;
 import com.usoftchina.bi.server.service.common.MessageLogService;
 import com.usoftchina.bi.server.service.dataSource.DataConnectorService;
+import org.apache.poi.hssf.usermodel.*;
+import org.apache.poi.hssf.util.HSSFCellUtil;
+import org.apache.poi.hssf.util.HSSFColor;
+import org.apache.poi.ss.format.CellFormatType;
+import org.apache.poi.ss.usermodel.*;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.BeanUtils;
@@ -33,6 +42,10 @@ import org.springframework.transaction.annotation.Transactional;
 import org.springframework.util.ObjectUtils;
 import org.springframework.util.StringUtils;
 
+import java.io.IOException;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.time.format.DateTimeFormatter;
 import java.util.*;
 
 @Service
@@ -53,6 +66,8 @@ public class DashboardsService {
     private MessageLogService messageLogService;
     @Autowired
     private DefaultDashboardService defaultDashboardService;
+    @Autowired
+    private DataConnectorMapper dataConnectorMapper;
 
     private static final Logger LOGGER = LoggerFactory.getLogger(DashboardsService.class);
 
@@ -420,4 +435,198 @@ public class DashboardsService {
         return new RepEntity(RepCode.success, dashboards.getId());
     }
 
+    /**
+     * 导出报表数据
+     * @param dashboardExportInfo
+     * @return
+     */
+    public HSSFWorkbook export(DashboardExportInfo dashboardExportInfo){
+        HSSFWorkbook workbook = new HSSFWorkbook();
+        int dashboardId = dashboardExportInfo.getDashboardId();
+        List<DataSourceExportInfo> dataSourceExportInfoList = dashboardExportInfo.getData();
+        for (DataSourceExportInfo dataInfo : dataSourceExportInfoList) {
+            RepEntity<DataConnector> repEntity = dataConnectorService.getConnector(dataInfo.getDataSourceId());
+            if (repEntity.getCode() == 200) {
+                DataConnector dataConnector = repEntity.getData();
+                String tableName = dataConnector.getLoadObject();
+                List<Screen> screenList = dataInfo.getFilter();
+                String condition = parseFilter(screenList);
+                List<Map<String, Object>> dataList = dataConnectorMapper.getExportData(tableName, condition);
+                List<ColumnRenameInfo> columnRenameInfo = JSON.parseArray(dataConnector.getColumnConfig(), ColumnRenameInfo.class);
+                createExcelSheet(workbook, dataConnector.getDataName(), dataList, columnRenameInfo);
+            }
+        }
+        return workbook;
+    }
+
+
+    private void createExcelSheet(HSSFWorkbook workbook, String sheetName, List<Map<String, Object>> dataList, List<ColumnRenameInfo> columnRenameInfo) {
+        //添加sheet
+        HSSFSheet sheet = workbook.createSheet(sheetName);
+        HSSFRow row = sheet.createRow(0);
+        HSSFCell cell;
+        HSSFCellStyle cellStyle = getCellStyle(workbook);
+        //设置标题
+        for (int i = 0, len = columnRenameInfo.size(); i < len; i++) {
+            cell = row.createCell(i);
+            cell.setCellStyle(cellStyle);
+            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
+            cell.setCellValue(columnRenameInfo.get(i).getColumnLable());
+        }
+        //设置数据
+        for (int i = 0, len = dataList.size(); i < len; i++) {
+            row = sheet.createRow(i + 1);
+            Map<String, Object> data = dataList.get(i);
+            for (int j = 0, size = columnRenameInfo.size(); j < size; j++) {
+                cell = row.createCell(j);
+                int dataType = convertToCellType(columnRenameInfo.get(j).getColumnType());
+                Object value = data.get(columnRenameInfo.get(j).getColumnName());
+                if (9 == dataType) {
+                    cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
+                    Date dataValue = null;
+                    try {
+                        dataValue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(String.valueOf(value));
+                    } catch (ParseException e) {
+                        continue;
+                    }
+                    cell.setCellValue(dataValue);
+                }else {
+                    cell.setCellType(dataType);
+                    cell.setCellValue(StringUtils.isEmpty(value) ? "" : String.valueOf(value));
+                }
+            }
+        }
+
+    }
+
+    private int convertToCellType(String columnType) {
+        switch (columnType) {
+            case "categorical":
+                return HSSFCell.CELL_TYPE_STRING;
+            case "Timestamp":
+                return 9;
+            case "BigDecimal":
+                return HSSFCell.CELL_TYPE_NUMERIC;
+            case "scale":
+                return HSSFCell.CELL_TYPE_NUMERIC;
+            default:
+                return HSSFCell.CELL_TYPE_STRING;
+        }
+    }
+
+    private HSSFCellStyle getCellStyle(HSSFWorkbook workbook) {
+        HSSFCellStyle style = workbook.createCellStyle();
+        Font font = workbook.createFont();
+        font.setFontName("仿宋_GB2312");// 字体
+        font.setFontHeightInPoints((short) 12);// 字号
+        font.setBoldweight(new Short("8"));
+        font.setColor((short)64);// 颜色
+        style.setFont(font);
+        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
+        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
+        style.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
+        style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
+        style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
+        style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
+        style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
+        return style;
+    }
+
+    private String parseFilter(List<Screen> screenList){
+        StringBuilder condition = new StringBuilder(" where 1=1 ");
+        if (CollectionUtils.isEmpty(screenList)) {
+            return null;
+        }
+        for (Screen screen : screenList) {
+            String columnName = screen.getColumnName();
+            String columnType = screen.getColumnType();
+            String symbol = screen.getSymbol();
+            String value = screen.getValue();
+            if (columnType != "time" && !("time".equals(columnType))) {
+                String symbVal = getSymbAndVal(symbol, value, columnType);
+                condition.append(" and " + columnName + " " + symbVal);
+            }else if (columnType == "time" || "time".equals(columnType)) {
+                String symbVal = getTimeSymbAndVal(symbol, value);
+                condition.append(" and " + columnName + " " + symbVal);
+            }
+        }
+        return condition.toString();
+    }
+
+    private String getTimeSymbAndVal(String symbol, String value) {
+        String values = "" + value;
+        String tar = "";
+        if ("between".equals(symbol)) {
+            String[] str = value.split(",");
+            String str1 = str[0];
+            String str2 = str[1];
+            tar = "between to_date('" + str1 + "','yyyy-MM-dd') and to_date('" + str2 + "','yyyy-MM-dd')";
+        } else {
+            tar = symbol + " '" + values + "'";
+        }
+        return tar;
+    }
+
+    private String getSymbAndVal(String symbol, String value, String columnType) {
+        String values = "" + value;
+        String tar = "";
+        if ("contain".equals(symbol)) {
+            if ("categorical".equals(columnType)) {
+                tar = "in " + getContainsCate(value);
+            } else {
+                tar = "like '%" + values + "%'";
+            }
+        } else if ("notContain".equals(symbol)) {
+            if ("categorical".equals(columnType)) {
+                tar = "not in " + getContainsCate(value);
+            } else {
+                tar = "not like '%" + values + "%'";
+            }
+        } else if ("startsWith".equals(symbol)) {
+            tar = "like '" + values + "%'";
+        } else if ("endsWith".equals(symbol)) {
+            tar = "like '%" + values + "'";
+        } else if ("null".equals(symbol)) {
+            tar = "is null";
+        } else if ("notNull".equals(symbol)) {
+            tar = "is not null";
+        } else if ("between".equals(symbol)) {
+            tar = "";
+            String[] str = value.split(",");
+            String str1 = str[0];
+            String str2 = str[1];
+            tar = "between '" + str1 + "' and '" + str2 + "'";
+        } else if("notInclude".equals(symbol)) {
+            tar = "not like '%" + values + "%'";
+        } else if("include".equals(symbol)){
+            tar = "like '%" + values + "%'";
+        } else if("equals".equals(symbol)){
+            tar = "=" + " '" + values + "'";
+        } else if("notEquals".equals(symbol)){
+            tar = "!=" + " '" + values + "'";
+        }else {
+            tar = symbol + " '" + values + "'";
+        }
+        return tar;
+    }
+
+    private String getContainsCate(String value) {
+        List<String> val = new ArrayList<>();
+        CollectionType javaType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, String.class);
+        try {
+            val = objectMapper.readValue(value, javaType);   //这里不需要强制转换
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+
+        String valueString = "";
+        Iterator isList = val.iterator();
+        while (isList.hasNext()) {
+            String v = String.valueOf(isList.next());
+            valueString = valueString + ", '" + v + "'";
+        }
+        valueString = valueString.replaceFirst(",", "(") + ")";
+        return valueString;
+    }
+
 }

+ 6 - 0
pom.xml

@@ -37,6 +37,7 @@
     <swagger.version>2.7.0</swagger.version>
     <mysql.version>6.0.6</mysql.version>
     <jwt.version>3.1.0</jwt.version>
+    <poi.version>3.9</poi.version>
   </properties>
 
   <repositories>
@@ -160,6 +161,11 @@
         <artifactId>mysql-connector-java</artifactId>
         <version>${mysql.version}</version>
       </dependency>
+      <dependency>
+        <groupId>org.apache.poi</groupId>
+        <artifactId>poi</artifactId>
+        <version>${poi.version}</version>
+      </dependency>
     </dependencies>
   </dependencyManagement>