Commit 566a2b12 by songzhenmin

feat:excel自定义报表导出

parent cc13564d
......@@ -118,6 +118,16 @@
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
</dependencies>
<build>
......
package com.hs.api.common.exceptions;
public class BIZConfigurationError extends ExceptionBase {
public BIZConfigurationError(String message) {
super(message);
}
}
......@@ -38,4 +38,6 @@ public class ExcelController {
String fileUrl = excelService.tableToXls(realPath,tableStr);
return Result.success(fileUrl);
}
}
package com.hs.api.controller;
import com.hs.api.common.Result;
import com.hs.api.common.annotations.Audit;
import com.hs.api.common.annotations.CurrentUser;
import com.hs.api.common.annotations.Token;
import com.hs.api.common.enums.AuditLogType;
import com.hs.api.common.handlers.GlobalExceptionHandler;
import com.hs.api.model.ExcelReport;
import com.hs.api.model.SysUser;
import com.hs.api.model.reqmodel.BlockValues;
import com.hs.api.model.reqmodel.BlockValuesNew;
import com.hs.api.model.reqmodel.ExcelReportsReq;
import com.hs.api.model.reqmodel.ExportReq;
import com.hs.api.model.respmodel.BlockValue;
import com.hs.api.service.BlockValuesService;
import com.hs.api.service.ExcelService;
import com.hs.api.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Api(tags = "板块数值Api")
@RestController
public class ReportController {
@Autowired
private BlockValuesService blockValuesService;
@Autowired
private UserService userServiceImpl;
@Autowired
private ExcelService excelService;
static final Logger log = LoggerFactory.getLogger(ReportController.class);
/**
* 根据pageId查询板块数值
*
* @return
* @throws Exception
*/
@PostMapping("reporttest")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("根据Page查询板块数值")
public Object getBlockValues_reporttest(@ApiIgnore @CurrentUser Long userId, @RequestBody BlockValues BlockValues) throws InterruptedException {
String getblockValues1 = userServiceImpl.selectBlockCode();
String getblockValues = getblockValues1.replace("#{time}",BlockValues.getTime().toString());
List<BlockValuesNew> blockvalueslist = JSONArray.parseArray(getblockValues,BlockValuesNew.class);
//List<BlockValue> list = blockValuesService.getBlockValuesByPageCodeNew(userId,blockValues.getPageCode(),blockValues.getDim());
List<BlockValue> list = blockValuesService.getBlockValuesByPageCodeNew(userId,blockvalueslist.get(0).getPageCode(),blockvalueslist.get(0).getDim());
return Result.success(list);
}
/**
* reportechart
*
* @return
* @throws Exception
*/
@PostMapping("reportechart")
@Token
@Audit(type = AuditLogType.REFRESH)
@ApiOperation("指标ECHARTS")
public Object getBlockValues_reportechart(@ApiIgnore @CurrentUser Long userId, @RequestBody BlockValues BlockValues) throws InterruptedException {
List<Map<String, Object>> reportEchartlist = userServiceImpl.selectReportEchart();
String datasourcesql="aaaa";
for (int i = 0; i < reportEchartlist.size(); i++) {
Map<String, Object> map = reportEchartlist.get(i);
Iterator it = map.keySet().iterator();
String str = (String) it.next();
System.out.print("key:"+str+"\t");
System.out.println("value:"+map.get(str));
if (str != null && !str.isEmpty() && str.equals("group_id")) {
List<Map<String, String>> grouptitletlist = userServiceImpl.selectGrouptitleByid(map.get(str).toString());
System.out.println("grouptitletlist:"+grouptitletlist.toString());
map.put("grouptitle",grouptitletlist);
List<Map<String, Object>> groupdatatlist = userServiceImpl.selectGroupdataByid(map.get(str).toString());
for (int i1 = 0; i1 < groupdatatlist.size(); i1++) {
Map<String, Object> mapdata1 = groupdatatlist.get(i1);
Iterator itdata1 = mapdata1.keySet().iterator();
while (itdata1.hasNext()) {
String datakeystr = (String) itdata1.next();
if (datakeystr != null && !datakeystr.isEmpty()) {
if (datakeystr != null && !datakeystr.isEmpty() && datakeystr.equals("data_source")) {
datasourcesql = mapdata1.get(datakeystr).toString();
System.out.println("datasourcesql:" + datasourcesql);
}
}
}
Map<String, Object> mapdata = groupdatatlist.get(i1);
Iterator itdata = mapdata.keySet().iterator();
while (itdata.hasNext()) {
String datakeystr = (String) itdata.next();
System.out.print("datakeystr:"+datakeystr+"\t");
System.out.println("datavalue:"+mapdata.get(datakeystr));
if (datakeystr != null && !datakeystr.isEmpty() && datakeystr.equals("groupdata_id")) {
List<Map<String, String>> datatitletlist = userServiceImpl.selectDatatitleByid(mapdata.get(datakeystr).toString());
System.out.println("datatitles:"+datatitletlist.toString());
mapdata.put("datatitles",datatitletlist);
String datasourcesqlnew = datasourcesql.replace("#{time}",BlockValues.getTime().toString());
System.out.println("datasourcesql:"+datasourcesql);
System.out.println("datasourcesqlnew:"+datasourcesqlnew);
List<Map<String, String>> datacontentlist= userServiceImpl.getdatacontentlist(datasourcesqlnew);
System.out.println("datatitles:"+datacontentlist.toString());
mapdata.put("datacontents",datacontentlist);
}
}
}
System.out.println("groupdatatlist:"+groupdatatlist.toString());
map.put("groupdata",groupdatatlist);
}
}
//
// List<Map<String, String>> grouptitletlist = userServiceImpl.selectGrouptileByid();
// String getblockValues1 = userServiceImpl.selectBlockCode();
// String getblockValues = getblockValues1.replace("#{time}",BlockValues.getTime().toString());
// List<BlockValuesNew> blockvalueslist = JSONArray.parseArray(getblockValues,BlockValuesNew.class);
// //List<BlockValue> list = blockValuesService.getBlockValuesByPageCodeNew(userId,blockValues.getPageCode(),blockValues.getDim());
// List<BlockValue> list = blockValuesService.getBlockValuesByPageCodeNew(userId,blockvalueslist.get(0).getPageCode(),blockvalueslist.get(0).getDim());
return Result.success(reportEchartlist);
}
/**
* 获取Excel简报模板列表
*
* @return
* @throws Exception
*/
@PostMapping("excelReportsList")
@Token
@ApiOperation("获取Excel简报模板列表")
public Object getExcelReportsList(@RequestBody ExcelReportsReq req) throws InterruptedException {
List<ExcelReport> exportsList = excelService.getExcelExportsList();
return Result.success(exportsList);
}
@PostMapping("exportExcel")
@ApiOperation("导出自定义Excel模板报表")
public Object exportExcel(HttpServletRequest request,@RequestBody ExportReq req) {
String realPath = request.getSession().getServletContext().getRealPath("/");
String excelUrl = excelService.exportExcel(realPath, req.getId(), req.getDate());
return Result.success(excelUrl);
}
}
\ No newline at end of file
package com.hs.api.mapper;
import com.hs.api.model.ExcelItemInfo;
import com.hs.api.model.ExcelReport;
import com.hs.api.model.SysConfig;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public interface SysExcelReportsMapper {
List<ExcelReport> getExcelExportsList();
List<ExcelReport> getExcelExportById(Long id);
List<ExcelItemInfo> getExcelItemByExcelId(Long exceld);
List<LinkedHashMap<String, String>> getDataList(String querySql);
}
\ No newline at end of file
package com.hs.api.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;
@Getter
@Component
public class ExcelItemInfo {
private Long id;
private Long excelId;
private boolean state;
private String sheetName;
private String blockIndex;
private int startRow;
private int startCol;
private String queryName;
private String querySql;
}
package com.hs.api.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;
import java.util.Date;
@Getter
@Component
public class ExcelReport {
private Long id;
@Setter
private boolean state;
@Setter
private String excelName;
@Setter
private String fileName;
private boolean isShow;
public boolean getIsShow() {
return isShow;
}
public void setIsShow(boolean isShow) {
isShow = isShow;
}
}
package com.hs.api.model.reqmodel;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
@ApiModel(description = "调用blockValues请求的数据")
@Data
public class ExcelReportsReq {
}
......@@ -7,4 +7,8 @@ import lombok.Data;
public class ExportReq {
@ApiModelProperty("Table Html")
private String tableStr;
@ApiModelProperty("id")
private Long id;
@ApiModelProperty("时间")
private String date;
}
package com.hs.api.service;
import com.hs.api.common.handlers.GlobalExceptionHandler;
import com.hs.api.model.ExcelReport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public interface ExcelService {
static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
String tableToXls(String realPath,String tableStr);
List<ExcelReport> getExcelExportsList();
String exportExcel(String realPath, Long id, String date);
}
package com.hs.api.service.Impl;
import com.hs.api.common.exceptions.BIZConfigurationError;
import com.hs.api.mapper.SysExcelReportsMapper;
import com.hs.api.model.ExcelItemInfo;
import com.hs.api.model.ExcelReport;
import com.hs.api.service.ExcelService;
import me.chyxion.xls.TableToXls;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.UUID;
import java.io.IOException;
import java.util.*;
@Service
public class ExcelServiceImpl implements ExcelService {
@Resource
SysExcelReportsMapper sysExcelReportsMapper;
@Override
public String tableToXls(String realPath,String tableStr) {
try{
......@@ -29,4 +46,168 @@ public class ExcelServiceImpl implements ExcelService {
}
return null;
}
public List<ExcelReport> getExcelExportsList() {
List<ExcelReport> excelExportsList = sysExcelReportsMapper.getExcelExportsList();
return excelExportsList;
}
public String exportExcel(String realPath,Long id, String date) {
List<ExcelReport> reports = sysExcelReportsMapper.getExcelExportById(id);
if (reports.size()>0) {
ExcelReport report = reports.get(0);
String templatePath = "/templates/" + report.getFileName();
String excelName = report.getExcelName();
try {
return create(id, date,templatePath,excelName, realPath);
} catch (IOException e) {
e.printStackTrace();
}
}else {
throw new BIZConfigurationError("未找到模板");
}
return null;
}
public String create(Long excelId, String date, String fileName, String excelName, String realPath) throws IOException {
File file = new File(fileName);
Workbook workBook = null;
if(file.getName().endsWith("xlsx")){
ClassPathResource classPathResource = new ClassPathResource(fileName);
File resourceFile = classPathResource.getFile();
workBook = new XSSFWorkbook(new FileInputStream(resourceFile));
}else if(file.getName().endsWith("xls")){
workBook = new HSSFWorkbook(new FileInputStream(file));
}
List<ExcelItemInfo> items = sysExcelReportsMapper.getExcelItemByExcelId(excelId);
for (ExcelItemInfo info: items) {
String sheetName = info.getSheetName();
int startRow = info.getStartRow();
int startCol = info.getStartCol();
String querySql = info.getQuerySql();
setSheet(workBook, sheetName, startRow, startCol, querySql, date);
}
File directory = new File(realPath + "/excel");
if(!directory.exists() && !directory.isDirectory()){
directory.mkdir();
}
File excel = new File(directory + "/" + excelName + "_" + date + ".xlsx");
FileOutputStream fosExcel = new FileOutputStream(excel);
workBook.write(fosExcel);
fosExcel.close();
workBook.close();
System.out.println("path= " + excel.getAbsolutePath());
return "excel/" + excel.getName();
}
private void setSheet(Workbook workBook, String sheetName, int startRow, int startCol, String querySql, String date) throws IOException{
int sheetIndex = workBook.getSheetIndex(sheetName);
if (sheetIndex==-1) return;
Sheet sheet = workBook.getSheetAt(sheetIndex);
XSSFCellStyle cellStyle = createCellStyle(workBook);
List<LinkedHashMap<String, String>> resultList = getResultList(date, querySql);
for (int i = 0; i < resultList.size(); i++) {
LinkedHashMap<String, String> map = resultList.get(i);
setMap(workBook, sheet, cellStyle, map, startRow, startCol, querySql);
startRow++;
}
}
public void setMap(Workbook workBook, Sheet sheet, XSSFCellStyle cellStyle, Map<String, String> map, int rowIndex, int colIndex, String querySql) {
Row row = sheet.getRow(rowIndex);
Set<Map.Entry<String , String>> set = map.entrySet();
Iterator<Map.Entry<String, String>> iter = set.iterator();
while(iter.hasNext()){
Map.Entry<String, String> me=iter.next();
Object meValue = me.getValue();
String value = meValue ==null?"": String.valueOf(meValue);
if (row==null) row = sheet.createRow(rowIndex);
Cell cell = row.getCell(colIndex);
if(cell==null) cell = row.createCell(colIndex);
cell.setCellValue(value);
setNumberFormat(workBook, cell);
cell.setCellStyle(cellStyle);
colIndex++;
}
}
public List<LinkedHashMap<String, String>> getResultList(String date, String querySql) {
querySql = querySql.replace("#{endtime}", date);
List<LinkedHashMap<String, String>> mapList = sysExcelReportsMapper.getDataList(querySql);
return mapList;
}
private XSSFCellStyle createCellStyle(Workbook workbook) {
XSSFCellStyle xssfCellStyle = ((XSSFWorkbook) workbook).createCellStyle();
xssfCellStyle.setAlignment(HorizontalAlignment.LEFT); //设置水平方向的对其方式
xssfCellStyle.setBorderTop(BorderStyle.THIN);
xssfCellStyle.setBorderLeft(BorderStyle.THIN);
xssfCellStyle.setBorderBottom(BorderStyle.THIN);
xssfCellStyle.setBorderRight(BorderStyle.THIN);
XSSFColor color = new XSSFColor(java.awt.Color.BLACK);
xssfCellStyle.setBottomBorderColor(color.getIndex());
xssfCellStyle.setRightBorderColor(color.getIndex());
xssfCellStyle.setTopBorderColor(color.getIndex());
xssfCellStyle.setLeftBorderColor(color.getIndex());
return xssfCellStyle;
}
public void setNumberFormat(Workbook workbook, Cell cell) {
//获取值并自己格式化
switch (cell.getCellType()) {
case STRING:// 字符串型
String strvalue = cell.getStringCellValue();
String strvalue2 = strvalue.replace("-", "");
strvalue2 = strvalue2.replace(".", "");
int dotindex = strvalue.indexOf(".");
int signindex = strvalue.indexOf("-");
if (strvalue2.chars().allMatch(Character::isDigit) && strvalue2.length() > 0 && signindex < 1) {
System.out.println("");
if (signindex == 0) strvalue = strvalue.replace("-", "");
if (dotindex == -1) {
XSSFDataFormat format = ((XSSFWorkbook)workbook).createDataFormat();
CellStyle style = workbook.createCellStyle();
style.setDataFormat(format.getFormat("0"));
cell.setCellStyle(style);
Double dvalue = new Double(cell.getRichStringCellValue().getString());
cell.setCellValue(dvalue);
cell.setCellType(CellType.NUMERIC);
}
if (dotindex > 0) {
//System.out.println("小数" + cell.getStringCellValue());
XSSFDataFormat format = ((XSSFWorkbook)workbook).createDataFormat();
CellStyle style = cell.getCellStyle();
style.setDataFormat(format.getFormat("0.00"));
cell.setCellStyle(style);
Double dvalue = new Double(cell.getRichStringCellValue().getString());
cell.setCellValue(dvalue);
cell.setCellType(CellType.NUMERIC);
}
}
break;
case NUMERIC:// 数值型
//System.out.println(cell.getNumericCellValue());
break;
case BOOLEAN:// 布尔
//System.out.println(cell.getBooleanCellValue());
break;
case FORMULA:// 公式型
// System.out.println(cell.getCellFormula());
break;
case BLANK:// 空值
//System.out.println();
break;
case ERROR: // 故障
//System.out.println();
break;
default:
//System.out.println();
}
}
}
......@@ -95,6 +95,12 @@ public class LoginServiceImpl implements LoginService {
//查询病案信息
SysVersion version = sysVersionMapper.selectLastDate();
//add 检查发布功能 by mengchao 2021-05-24 begin
if(sysConfigService.getStateByKey(SysConfigKeyType.BAH_CXRQ_CONTROL.getCode()) && !user.getIsAdmin())
{
version.setBahDate(version.getBahDate()-1);
}
// add end
loginInfo.setVersion(version);
RedisUtil.del(user.getUserCode());
} else {
......
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hs.api.mapper.SysExcelReportsMapper">
<resultMap id="ReportMap" type="com.hs.api.model.ExcelReport">
<id column="excel_id" jdbcType="DECIMAL" property="id"/>
<result column="STATE" jdbcType="BOOLEAN" property="state"/>
<result column="excel_name" jdbcType="VARCHAR" property="excelName"/>
<result column="file_name" jdbcType="VARCHAR" property="fileName"/>
<result column="is_show" jdbcType="BOOLEAN" property="isShow"/>
</resultMap>
<resultMap id="ItemMap" type="com.hs.api.model.ExcelItemInfo">
<id column="id" jdbcType="DECIMAL" property="id"/>
<result column="STATE" jdbcType="BOOLEAN" property="state"/>
<result column="EXCEL_ID" jdbcType="VARCHAR" property="excelId"/>
<result column="SHEET_NAME" jdbcType="VARCHAR" property="sheetName"/>
<result column="BLOCK_INDEX" jdbcType="BOOLEAN" property="blockIndex"/>
<result column="START_ROW" jdbcType="BOOLEAN" property="startRow"/>
<result column="START_COL" jdbcType="VARCHAR" property="startCol"/>
<result column="QUERY_NAME" jdbcType="VARCHAR" property="queryName"/>
<result column="QUERY_SQL" jdbcType="BOOLEAN" property="querySql"/>
</resultMap>
<select id="getExcelExportsList" resultMap="ReportMap">
select *
from sys_excel_report
where state=1 and is_show=1
</select>
<select id="getExcelExportById" resultMap="ReportMap">
select *
from sys_excel_report
where excel_id = ${id}
</select>
<select id="getExcelItemByExcelId" resultMap="ItemMap">
select *
from sys_excel_item_info
where excel_id = ${id}
</select>
<select id="getDataList" resultType="java.util.LinkedHashMap">
${querySql}
</select>
</mapper>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment