前言
做這個專案的思路是由于公司基于自身發展,需要將之前的老專案平臺拆解出來,由于之前的專案是所有的功能全部集中在一起,學習成本以及后續的擴展性來說,非常的不友好,并且由于之前設計人員的流失導致了專案無法進一步優化,所以想將其進行拆解,將單個功能模塊進行拆分,形成微服務化,使每個功能的業務更加單一,也更加簡單
經過使用了一段時間的老平臺,發現目前公司的平臺的一些設計確實非常的好,其中,報表的設計理念比市面上大多的報表工具設計都要好,為什么呢,因為我們公司是基于B to B的專案模式,所以,客戶可能會經常臨時性的提出一些報表需求,并且需要回應時間比較快速,所以我們需要一種基于模版即可生成報表的報表工具
報表工具的比對
基于模版形式的報表工具
目前市場上基于模版的是JXLS,他的優勢是JXLS 是基于 Jakarta POI API 的 Excel 報表生成工具,可以生成精美的 Excel 格式報表,它采用標簽的方式,類似 JSP 標簽,寫一個 Excel 模板,然后生成報表,非常靈活,簡單!
缺點是它只可以匯出03版本的excel
實作jxls
配置與使用
-
引入依賴
<dependency> <groupId>org.jxls</groupId> <artifactId>jxls</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>org.jxls</groupId> <artifactId>jxls-poi</artifactId> <version>1.0.15</version> </dependency> <dependency> <groupId>net.sf.jxls</groupId> <artifactId>jxls-core</artifactId> <version>1.0.5</version> </dependency> -
撰寫工具輔助類
研發一個execl生成的工具類,其中加入了自定義方法,這個思想與lims平臺設計中的Alog類類似,采用Jexl來進行實作,本專案采用的是jexl3
package com.thyc.reportserver.utils; import com.thyc.reportserver.excelCal.CalTime; import org.apache.commons.jexl3.JexlBuilder; import org.apache.commons.jexl3.JexlEngine; import org.jxls.area.Area; import org.jxls.builder.AreaBuilder; import org.jxls.builder.xls.XlsCommentAreaBuilder; import org.jxls.common.CellRef; import org.jxls.common.Context; import org.jxls.expression.JexlExpressionEvaluator; import org.jxls.transform.Transformer; import org.jxls.util.TransformerFactory; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * @Description: excel輔助工具類 * @Author: wanping * @Date: 6/13/23 **/ public class ExcelUtils { /*** * excel匯出到response * @param fileName 匯出檔案名 * @param templateFile 模板檔案地址 * @param params 資料集合 * @param response response */ public static void exportExcel(String fileName, InputStream templateFile, Map<String, Object> params, HttpServletResponse response) throws IOException { response.reset(); response.setHeader("Accept-Ranges", "bytes"); OutputStream os = null; response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName)); response.setContentType("application/octet-stream;charset=UTF-8"); try { os = response.getOutputStream(); exportExcel(templateFile, params, os); } catch (IOException e) { throw e; } } /** * 匯出excel到輸出流中 * @param templateFile 模板檔案 * @param params 傳入引數 * @param os 輸出流 * @throws IOException */ public static void exportExcel(InputStream templateFile, Map<String, Object> params, OutputStream os) throws IOException { try { Context context = new Context(); Set<String> keySet = params.keySet(); for (String key : keySet) { //設定引數變數 context.putVar(key, params.get(key)); } Map<String, Object> myFunction = new HashMap<>(); myFunction.put("calTime", new CalTime()); // 啟動新的jxls-api 加載自定義方法 Transformer trans = TransformerFactory.createTransformer(templateFile, os); JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) trans.getTransformationConfig().getExpressionEvaluator(); // evaluator.getJexlEngine().setFunctions(myFunction); 這個方法是2版本的 JexlBuilder jb = new JexlBuilder(); jb.namespaces(myFunction); JexlEngine je = jb.create(); evaluator.setJexlEngine(je); // 載入模板、處理匯出 AreaBuilder areaBuilder = new XlsCommentAreaBuilder(trans); List<Area> areaList = areaBuilder.build(); areaList.get(0).applyAt(new CellRef("sheet1!A1"), context); trans.write(); } catch (IOException e) { throw e; } finally { try { if (os != null) { os.flush(); os.close(); } if (templateFile != null) { templateFile.close(); } } catch (IOException e) { throw e; } } } } -
撰寫計算類
package com.thyc.reportserver.excelCal; import org.jxls.transform.poi.WritableCellValue; import org.jxls.transform.poi.WritableHyperlink; import java.text.SimpleDateFormat; import java.util.Date; /** * @Description: excel計算時間方法 * @Author: wanping * @Date: 6/13/23 **/ public class CalTime { /** * 格式化時間 */ public Object formatDate(Date date) { if (date != null) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateStr = sdf.format(date); return dateStr; } return "--"; } /** * 設定超鏈接方法 */ public WritableCellValue getLink(String address, String title) { return new WritableHyperlink(address, title); } } -
撰寫剩下的測驗用例
service
package com.thyc.reportserver.service; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.OutputStream; import java.util.Map; /** * @Description: TODO * @Author: wanping * @Date: 6/13/23 **/ public interface ExcelService { /** * 匯出excel,寫入檔案中 * @param templateFile * @param params * @param outputFile * @return */ boolean getExcel(String templateFile, Map<String,Object> params, File outputFile); }impl
package com.thyc.reportserver.service.impl; import com.thyc.reportserver.service.ExcelService; import com.thyc.reportserver.utils.ExcelUtils; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.ResourceUtils; import java.io.*; import java.util.Map; /** * @Description: TODO * @Author: wanping * @Date: 6/13/23 **/ @Service public class ExcelServiceImpl implements ExcelService { private Logger logger = LoggerFactory.getLogger(getClass()); /** * 模板檔案的基礎路徑 */ @Value("${jxls.template.path}") private String templatePath; @Override public boolean getExcel(String templateFile, Map<String, Object> params, File outputFile) { FileInputStream inputStream = null; try { //獲取模板檔案的輸入流 inputStream = new FileInputStream(ResourceUtils.getFile(templatePath + templateFile)); File dFile = outputFile.getParentFile(); //檔案夾不存在時創建檔案夾 if(dFile.isDirectory()){ if(!dFile.exists()){ dFile.mkdir(); } } //檔案不存在時創建檔案 if(!outputFile.exists()){ outputFile.createNewFile(); } //匯出excel檔案 ExcelUtils.exportExcel(inputStream, params, new FileOutputStream(outputFile)); } catch (IOException e) { logger.error("excel export has error" + e); return false; } return true; } }撰寫測驗用例
package com.thyc.reportserver; import com.thyc.reportserver.excelModel.UserModel; import com.thyc.reportserver.service.ExcelService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.io.File; import java.util.*; @SpringBootTest class ReportServerApplicationTests { @Autowired ExcelService excelService; @Test void contextLoads() { Map<String, Object> params = new HashMap(); List<UserModel> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { int i1 = i + 1; list.add(new UserModel(i1, "test" + i1, "男", 25 + i, "tttttttttt" + i1, new Date(), "htpp://wwww.baidu.com")); } params.put("list", list); excelService.getExcel("user1.xlsx", params, new File("/Users/wanping/IdeaProjects/ddd/report-server/excel/test01.xlsx")); } }- 結果展示
匯入模版

結果

參考:https://www.jb51.net/article/195015.htm
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/555110.html
標籤:其他
下一篇:返回列表
