- sql查询,把查出来的数据填充到jasper中
- 前端直接把页面上的数据以json格式传过来
- 导入依赖
net.sf.jasperreports
jasperreports
6.4.0
org.projectlombok
lombok
1.18.0
provided
org.apache.commons
commons-collections4
4.2
- 把需要的参数封装为一个VO,这里把需要的参数都放进了PrintParamRequest这个类中,主要有三个字段
@Data
public class PrintParamRequest implements Serializable {
private static final long serialVersionUID = 1L;
// jasper模板名称
private String templateName;
// 数据
private String content;
// 填充方式
private String type;
}
- 创建返回的VO
@Data
public class PrintParamResponse implements Serializable {
private static final long serialVersionUID = 1L;
// 返回编码
private long code;
// 返回信息
private String message ;
}
- SQL填充方式的VO,这里的字段看实际情况,因这里SQL填充的报表都是用这几个字段来查询的,所以封装成一个VO类
@Data
public class SqlPrintParam implements Serializable {
private static final long serialVersionUID = 1L;
// 租户编号
private Integer tenant_num_id;
// 环境:测试6、生产8
private Integer data_sign;
// 单号
private Long balane_no;
private Integer sub_unit_num_id;
}
- 创建打印接口
public interface PrintReportService {
PrintParamResponse printReport(PrintParamRequest request)
throws IOException, SQLException, JRException;
}
- 打印实现,这里使用的是html打印,可以换成excel、pdf的等等,看实际需求,其中自定义了一些异常
import com.alibaba.dubbo.config.annotation.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.learn.soa.print.exception.PageOutOfRangeRuntimeException;
import com.learn.soa.print.exception.SystemRuntimeException;
import com.learn.soa.print.model.SqlPrintParam;
import com.learn.soa.print.request.PrintParamRequest;
import com.learn.soa.print.response.PrintParamResponse;
import com.learn.soa.print.service.PrintReportService;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.sql.DataSource;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRPrintPage;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JsonDataSource;
import net.sf.jasperreports.engine.export.HtmlExporter;
import net.sf.jasperreports.export.Exporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleHtmlExporterOutput;
import net.sf.jasperreports.export.SimpleHtmlReportConfiguration;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
/**
* @author wudhk
* @descriptin 报表打印dubbo服务
*/
@Service
public class PrintReportServiceImpl implements PrintReportService {
private static final Logger LOGGER = LoggerFactory.getLogger(PrintReportServiceImpl.class);
@Autowired
@Qualifier("dataSource")
private DataSource dataSource;
@Autowired
private ObjectMapper objectMapper;
@Override
public PrintParamResponse printReport(PrintParamRequest buckleParamRequest) {
LOGGER.info("获取入参:request:[{}]", buckleParamRequest);
PrintParamResponse response = new PrintParamResponse();
String content = buckleParamRequest.getContent();
String templateName = buckleParamRequest.getTemplateName();
String type = buckleParamRequest.getType();
LOGGER.info("获取参数值:templateName:[{}],type:[{}],content:[{}]", templateName, type, content);
String msg = null;
if (StringUtils.isEmpty(content)) {
msg = String.format("未传入有效数据");
response.setMessage(msg);
return response;
}
InputStream is =
this.getClass().getResourceAsStream("/print-template/" + templateName + ".jasper");
if (is == null) {
msg = String.format("打印模板不存在,请联系系统管理员。");
}
ByteArrayOutputStream outputStream = null;
SqlPrintParam reportParamObj;
try {
if ("sql-print".equals(type)) {
reportParamObj = objectMapper.readValue(content, SqlPrintParam.class);
Map reportParams = createReportParam(reportParamObj);
outputStream = createReport(reportParams, is);
} else {
ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes());
JRDataSource jsonDataSource = new JsonDataSource(bis);
outputStream = createReport(jsonDataSource, is);
}
LOGGER.info("打印内容:{}", outputStream);
if (Objects.nonNull(outputStream) && outputStream.size() > 0) {
msg = new String(outputStream.toByteArray());
} else {
msg = String.format("没有查询到数据!");
}
} catch (JRException | SystemRuntimeException e) {
msg = String.format("发生系统未知异常:%d", e.getMessage());
} catch (IOException e) {
msg = String.format("json 转换异常,json字符串:%d,类型:%d", content, "BuckleParam");
} catch (PageOutOfRangeRuntimeException e) {
msg = String.format("已到达最后一页!");
}
LOGGER.info("msg:[{}]", msg);
response.setMessage(msg);
return response;
}
/**
* @param reportParams
* @param is
* @return java.io.ByteArrayOutputStream
* @description SQL填充方式
*/
public ByteArrayOutputStream createReport(Map reportParams, InputStream is) {
Connection con = null;
ByteArrayOutputStream out = null;
Exporter exporter;
JasperPrint jasperPrint;
try {
out = new ByteArrayOutputStream();
exporter = new HtmlExporter();
con = dataSource.getConnection();
SimpleHtmlReportConfiguration simpleHtmlReportConfiguration = new SimpleHtmlReportConfiguration();
simpleHtmlReportConfiguration.setPageIndex(null);
jasperPrint = JasperFillManager.fillReport(is, reportParams, con);
exporter.setConfiguration(simpleHtmlReportConfiguration);
exporter.setExporterOutput(new SimpleHtmlExporterOutput(out));
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.exportReport();
} catch (JRException | SQLException e) {
LOGGER.error("ERROR:", e);
throw new SystemRuntimeException(e);
} catch (JRRuntimeException e) {
if (e.getMessage().indexOf("Page index out of range") > -1) {
LOGGER.warn("WARN:", e);
throw new PageOutOfRangeRuntimeException(e);
} else {
LOGGER.error("ERROR", e);
throw new SystemRuntimeException(e);
}
} finally {
try {
if (out != null) {
out.close();
}
if (is != null) {
is.close();
}
if (con != null) {
con.close();
}
} catch (IOException e) {
LOGGER.error("ERROR", e);
} catch (SQLException e) {
LOGGER.error("ERROR", e);
}
}
if (Objects.nonNull(jasperPrint)) {
List pages = jasperPrint.getPages();
if (CollectionUtils.isEmpty(pages)
|| CollectionUtils.isNotEmpty(pages) && pages.get(0).getElements().size() == 0) {
out = null;
}
}
return out;
}
/**
* @param jsonDataSource
* @param is
* @return java.io.ByteArrayOutputStream
* @description JSON数据填充方式
*/
public ByteArrayOutputStream createReport(JRDataSource jsonDataSource, InputStream is) {
ByteArrayOutputStream out = null;
Exporter exporter;
JasperPrint jasperPrint;
try {
exporter = new HtmlExporter();
out = new ByteArrayOutputStream();
SimpleHtmlReportConfiguration simpleHtmlReportConfiguration = new SimpleHtmlReportConfiguration();
simpleHtmlReportConfiguration.setEmbedImage(true);
// 报表填充
jasperPrint = JasperFillManager.fillReport(is, null, jsonDataSource);
exporter.setConfiguration(simpleHtmlReportConfiguration);
//生成输出流
exporter.setExporterOutput(new SimpleHtmlExporterOutput(out));
//创建jasperPrint
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.exportReport();
} catch (JRException e) {
LOGGER.error("ERROR:", e);
throw new SystemRuntimeException(e);
} finally {
try {
if (out != null) {
out.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
LOGGER.error("ERROR", e);
}
}
return out;
}
/**
* @description 创建sql运行时需要的参数
**/
public static Map createReportParam(SqlPrintParam reportParamObj) {
Map map = new HashMap<>();
Long balanceNo = reportParamObj.getBalane_no();
Integer dataSign = reportParamObj.getData_sign();
Integer tenantNumId = reportParamObj.getTenant_num_id();
Integer subUnitNumId = reportParamObj.getSub_unit_num_id();
map.put("dataSign", dataSign);
map.put("tenantNumId", tenantNumId);
if (balanceNo != null) {
map.put("balanceNo", balanceNo);
}
if (subUnitNumId != null) {
map.put("subUnitNumId", " AND dtl.SUB_UNIT_NUM_ID=" + subUnitNumId);
}
return map;
}
}