电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導出,在線文件導出)

瀏覽:4日期:2023-04-27 16:11:19

在項目持續集成的過程中,有時候需要實現報表導出和文檔導出,類似于excel中這種文檔的導出,在要求不高的情況下,有人可能會考慮直接導出csv文件來簡化導出過程。但是導出xlsx文件,其實過程相對更復雜。解決方案就是使用poi的jar包。使用源生的poi來操作表格,代碼冗余,處理復雜,同時poi的相關聯的依賴還會存在版本兼容問題。所以直接使用poi來實現表格導出,維護成本大,不易于拓展。

我們需要學會站在巨人的肩膀上解決問題,jxls-poi這個就很好解決這個excel表格導出的多樣化的問題。類似jsp和thymealf的模板定義,使得表格導出變得簡單可控。

不多BB上代碼

1.引入關鍵依賴包

<!-- jxls-api依賴 --><dependency><groupId>org.jxls</groupId><artifactId>jxls-poi</artifactId><version>1.0.15</version></dependency><dependency><groupId>org.jxls</groupId><artifactId>jxls</artifactId><version>2.4.6</version></dependency>

這里只需要兩個依賴便操作excel表格了。

2.定義模板文件

SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導出,在線文件導出)

新建一個excel文件,后綴名為.xlsx,在resources目錄下新增一個jxls的文件夾,把模板文件放在這個文件夾下,便于后續的spring-boot的集成。

3.導出工具類

/** * @author machenike */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('fun', new ExcelUtils()); // 啟動新的jxls-api 加載自定義方法 Transformer trans = TransformerFactory.createTransformer(templateFile, os); JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) trans.getTransformationConfig().getExpressionEvaluator(); evaluator.getJexlEngine().setFunctions(myFunction); // 載入模板、處理導出 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; } } } /** * 格式化時間 */ 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); }}

這個工具類中我定義兩個導出用的方法一個是直接是HttpServletResponse 導出在線下載文件一個使用輸入流導出同時模板中還支持方法傳入。

4.定義導出服務類

全局配置jxls模板的基礎路徑

#jxls模板的基礎路徑jxls.template.path: classpath:jxls/

定義服務接口

/** * excel用service */public interface ExcelService { /** * 導出excel,寫入輸出流中 * @param templateFile * @param params * @param os * @return */ boolean getExcel(String templateFile,Map<String,Object> params, OutputStream os); /** * 導出excel,寫入response中 * @param templateFile * @param fileName * @param params * @param response * @return */ boolean getExcel(String templateFile,String fileName, Map<String,Object> params, HttpServletResponse response); /** * 導出excel,寫入文件中 * @param templateFile * @param params * @param outputFile * @return */ boolean getExcel(String templateFile, Map<String,Object> params, File outputFile);}

excel導出用服務實現類

/** * excel用serviceImpl */@Servicepublic class ExcelServiceImppl implements ExcelService { private static final Logger logger = LoggerFactory.getLogger(ExcelServiceImppl.class); /** * 模板文件的基礎路徑 */ @Value('${jxls.template.path}') private String templatePath; @Override public boolean getExcel(String templateFile, Map<String, Object> params, OutputStream os) { FileInputStream inputStream = null; try { //獲取模板文件的輸入流 inputStream = new FileInputStream(ResourceUtils.getFile(templatePath + templateFile)); //導出文件到輸出流 ExcelUtils.exportExcel(inputStream, params, os); } catch (IOException e) { logger.error('excel export has error' + e); return false; } return true; } @Override public boolean getExcel(String templateFile, String fileName, Map<String, Object> params, HttpServletResponse response) { FileInputStream inputStream = null; try { //獲取模板文件的輸入流 inputStream = new FileInputStream(ResourceUtils.getFile(templatePath + templateFile)); //導出文件到response ExcelUtils.exportExcel(fileName,inputStream,params,response); } catch (IOException e) { logger.error('excel export has error' + e); return false; } return true; } @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; }}

如上,服務類提供了,三種導出的實現方法

導出excel寫入response中 導出excel寫入輸出流中 導出excel寫入文件中

這三種方法足以覆蓋所有的業務需求

5.編輯jxls模板

這里為方便導出最好定義與模板匹配的實體類,便于數據的裝載和導出

public class UserModel { private Integer id; private String name; private String sex; private Integer age; private String remark; private Date date; private String link; }

SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導出,在線文件導出)

插入標注定義模板,定義迭代對象jx:each

jx:each(items='list' var='item' lastCell='G3')

上面G3 模板中迭代的結束位置,然后用類似EL表達式的方式填充到模板當中

SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導出,在線文件導出)

填寫范圍jx:area

jx:area(lastCell='G3')

模板編輯完成后保存即可,

6.代碼測試使用

導出為本地文件

@SpringBootTestclass BlogJxlsApplicationTests { @Autowired ExcelService excelService; @Test void contextLoads() { Map<String, Object> params = new HashMap(); List<UserModel> list = new ArrayList<>(); list.add(new UserModel(1, 'test01', '男', 25, 'tttttttttt',new Date(),'htpp://wwww.baidu.com')); list.add(new UserModel(2, 'test02', '男', 20, 'tttttttttt',new Date(),'htpp://wwww.baidu.com')); list.add(new UserModel(3, 'test04', '女', 25, 'ttttddddasdadatttttt',new Date(),'htpp://wwww.baidu.com')); list.add(new UserModel(4, 'test08', '男', 20, 'ttttttdasdatttt',new Date(),'htpp://wwww.baidu.com')); list.add(new UserModel(5, 'test021', '女', 25, 'ttttdatttttt',new Date(),'htpp://wwww.baidu.com')); list.add(new UserModel(7, 'test041', '男', 25, 'ttdadatttttttt',new Date(),'htpp://wwww.baidu.com'));params.put('list', list); excelService.getExcel('t1.xlsx', params, new File('D:test05.xlsx')); }}

導出成功

SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導出,在線文件導出)

在線導出文件

@RestControllerpublic class TestController { @Autowired ExcelService excelService; @RequestMapping('test') public void testFile(HttpServletResponse response){ Map<String, Object> params = new HashMap(); List<UserModel> list = new ArrayList<>(); list.add(new UserModel(1, 'test01', '男', 25, 'tttttttttt',new Date(),'htpp://wwww.baidu.com')); list.add(new UserModel(2, 'test02', '男', 20, 'tttttttttt',new Date(),'htpp://wwww.baidu.com')); list.add(new UserModel(3, 'test04', '女', 25, 'ttttddddasdadatttttt',new Date(),'htpp://wwww.baidu.com')); list.add(new UserModel(4, 'test08', '男', 20, 'ttttttdasdatttt',new Date(),'htpp://wwww.baidu.com')); list.add(new UserModel(5, 'test021', '女', 25, 'ttttdatttttt',new Date(),'htpp://wwww.baidu.com')); list.add(new UserModel(7, 'test041', '男', 25, 'ttdadatttttttt',new Date(),'htpp://wwww.baidu.com')); params.put('list', list); excelService.getExcel('t1.xlsx',System.currentTimeMillis()+'.xlsx', params,response); }}

SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導出,在線文件導出)

導出成功

SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導出,在線文件導出)

SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導出,在線文件導出)

源碼地址https://github.com/DavidLei08/BlogJxls.git

到此這篇關于SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導出,在線文件導出)的文章就介紹到這了,更多相關SpringBoot集成jxls-poi內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
主站蜘蛛池模板: Maneurop/美优乐压缩机,活塞压缩机,型号规格,技术参数,尺寸图片,价格经销商 | 三佳互联一站式网站建设服务|网站开发|网站设计|网站搭建服务商 赛默飞Thermo veritiproPCR仪|ProFlex3 x 32PCR系统|Countess3细胞计数仪|371|3111二氧化碳培养箱|Mirco17R|Mirco21R离心机|仟诺生物 | 密集柜_档案密集柜_智能密集架_密集柜厂家_密集架价格-智英伟业 密集架-密集柜厂家-智能档案密集架-自动选层柜订做-河北风顺金属制品有限公司 | 罐体电伴热工程-消防管道电伴热带厂家-山东沃安电气 | 申江储气罐厂家,储气罐批发价格,储气罐规格-上海申江压力容器有限公司(厂) | 小青瓦丨古建筑瓦丨青瓦厂家-宜兴市徽派古典建筑材料有限公司 | 手机存放柜,超市储物柜,电子储物柜,自动寄存柜,行李寄存柜,自动存包柜,条码存包柜-上海天琪实业有限公司 | 广东成考网-广东成人高考网 | Brotu | 关注AI,Web3.0,VR/AR,GPT,元宇宙区块链数字产业 | 反渗透阻垢剂-缓蚀阻垢剂厂家-循环水处理药剂-山东鲁东环保科技有限公司 | 游泳池设计|设备|配件|药品|吸污机-东莞市太平洋康体设施有限公司 | 并网柜,汇流箱,电控设备,中高低压开关柜,电气电力成套设备,PLC控制设备订制厂家,江苏昌伟业新能源科技有限公司 | 冲击式破碎机-冲击式制砂机-移动碎石机厂家_青州市富康机械有限公司 | 洗瓶机厂家-酒瓶玻璃瓶冲瓶机-瓶子烘干机-封口旋盖压盖打塞机_青州惠联灌装机械 | 黄石东方妇产医院_黄石妇科医院哪家好_黄石无痛人流医院 | 武汉天安盾电子设备有限公司 - 安盾安检,武汉安检门,武汉安检机,武汉金属探测器,武汉测温安检门,武汉X光行李安检机,武汉防爆罐,武汉车底安全检查,武汉液体探测仪,武汉安检防爆设备 | 北京浩云律师事务所-法律顾问_企业法务_律师顾问_公司顾问 | EDLC超级法拉电容器_LIC锂离子超级电容_超级电容模组_软包单体电容电池_轴向薄膜电力电容器_深圳佳名兴电容有限公司_JMX专注中高端品牌电容生产厂家 | 网架支座@球铰支座@钢结构支座@成品支座厂家@万向滑动支座_桥兴工程橡胶有限公司 | 上海电子秤厂家,电子秤厂家价格,上海吊秤厂家,吊秤供应价格-上海佳宜电子科技有限公司 | 洛阳永磁工业大吊扇研发生产-工厂通风降温解决方案提供商-中实洛阳环境科技有限公司 | ET3000双钳形接地电阻测试仪_ZSR10A直流_SXJS-IV智能_SX-9000全自动油介质损耗测试仪-上海康登 | 高低温试验房-深圳高低温湿热箱-小型高低温冲击试验箱-爱佩试验设备 | 铝机箱_铝外壳加工_铝外壳厂家_CNC散热器加工-惠州市铂源五金制品有限公司 | 吸污车_吸粪车_抽粪车_电动三轮吸粪车_真空吸污车_高压清洗吸污车-远大汽车制造有限公司 | 嘉兴泰东园林景观工程有限公司_花箱护栏| 铝板冲孔网,不锈钢冲孔网,圆孔冲孔网板,鳄鱼嘴-鱼眼防滑板,盾构走道板-江拓数控冲孔网厂-河北江拓丝网有限公司 | 成都治疗尖锐湿疣比较好的医院-成都治疗尖锐湿疣那家医院好-成都西南皮肤病医院 | 东莞市踏板石餐饮管理有限公司_正宗桂林米粉_正宗桂林米粉加盟_桂林米粉加盟费-东莞市棒子桂林米粉 | 上海瑶恒实业有限公司|消防泵泵|离心泵|官网 | 培训中心-海南香蕉蛋糕加盟店技术翰香原中心官网总部 | 工业CT-无锡璟能智能仪器有限公司 | 澳门精准正版免费大全,2025新澳门全年免费,新澳天天开奖免费资料大全最新,新澳2025今晚开奖资料,新澳马今天最快最新图库-首页-东莞市傲马网络科技有限公司 | 冷却塔厂家_冷却塔维修_冷却塔改造_凉水塔配件填料公司- 广东康明节能空调有限公司 | 东莞螺丝|东莞螺丝厂|东莞不锈钢螺丝|东莞组合螺丝|东莞精密螺丝厂家-东莞利浩五金专业紧固件厂家 | 胃口福饺子加盟官网_新鲜现包饺子云吞加盟 - 【胃口福唯一官网】 | 意大利Frascold/富士豪压缩机_富士豪半封闭压缩机_富士豪活塞压缩机_富士豪螺杆压缩机 | PVC快速门-硬质快速门-洁净室快速门品牌厂家-苏州西朗门业 | 集装袋吨袋生产厂家-噸袋廠傢-塑料编织袋-纸塑复合袋-二手吨袋-太空袋-曹县建烨包装 | 超声波焊接机_超音波熔接机_超声波塑焊机十大品牌_塑料超声波焊接设备厂家 | 考勤系统_考勤管理系统_网络考勤软件_政企|集团|工厂复杂考勤工时统计排班管理系统_天时考勤 |