大佬教程收集整理的这篇文章主要介绍了Angular/Spring Boot Rest API下载Word文档,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
使用POI XWPF生成Word文档,引入POI:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency>
项目中经常从Word模板生成文档,下面示例演示了替换文档内容的方法。模版中要替换的内容以${}标识,调用XWPFRun.setText()方法更新文档。
package org.iata.caimS.Util; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import java.io.byteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.List; import java.util.Map; import static org.springframework.util.StringUtils.isEmpty; public class XWPFDocumentUtils { public static byte[] replaceDocument(String path,Map<String,String> fields) throws IOException { try (XWPFDocument doc = new XWPFDocument(new FileInputStream(path))) { for (XWPFParagraph paragraph : doc.getParagraphs()) { String paragraphText = paragraph.getText(); if (!paragraphText.contains("${")) { conTinue; } for (Map.Entry<String,String> field : fields.entrySet()) { String find = "${" + field.getKey() + "}"; if (!paragraphText.contains(find)) { conTinue; } List<XWPFRun> runs = paragraph.getRuns(); for (int i = 0; i < runs.size(); i++) { XWPFRun run = runs.get(i); String text = run.text(); if (isEmpty(text)) { conTinue; } if (text.contains("${") || (text.contains("$") && runs.get(i + 1).text().startsWith("{"))) { while (!text.contains("}")) { text += runs.get(i + 1).text(); paragraph.removeRun(i + 1); } run.setText(text.contains(find) ? text.replace(find,field.getValue()) : text,0); } } } } try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { doc.write(out); return out.toByteArray(); } } } }
调用replaceDocument()方法生成word文档,如要在Rest API中定义文件名称,使用ResponseEntity并增加header,否则可以直接返回byte[]。
@GetMapping("/api/doc/{heroNamE}") public ResponseEntity<byte[]> getDocument(@PathVariable String heroName) { try { Map<String,String> fields = new HashMap<>(); fields.put("hero_name",heroName); fields.put("create_date","2019年6月"); byte[] bytes = XWPFDocumentUtil.replaceDocument("template/hero.docx",fields); httpHeaders headers = new httpHeaders(); headers.add("Content-Disposition","attachment;filename=hero.docx"); return ResponseEntity.ok().headers(headers).body(bytes); } catch (Exception E) { throw new XWPFDocumentexception(e.getmessage()); } }
配置CORS的ExposedHeaders,否则前台不能读取"Content-Disposition":
@Bean CorsConfigurationsource corsConfigurationsource() { CorsConfiguration configuration = new CorsConfiguration(); SecurityProperties.Cors cors = config.getCors(); configuration.setAllowedMethods(Arrays.asList("*")); configuration.setAllowedHeaders(Arrays.asList("Accept","Accept-Encoding","Accept-Language","Authorization","Connection","Content-Type","Host","Origin","Referer","User-Agent","X-requested-With")); configuration.setExposedHeaders(Arrays.asList("Content-Disposition")); UrlBasedCorsConfigurationsource source = new UrlBasedCorsConfigurationsource(); source.registerCorsConfiguration("/**",configuration); return source; }
可以使用链接直接访问REST URL下载文档,若项目启用了JWT Token验证,则必须使用httpClient的get方法。
本文使用了FileSaver.js保存文档,开始之前先安装:
npm install --save file-saver
"paths": { "file-saver": [ "node_modules/file-saver/dist/FileSaver.js" ] }
下载方法:
import * as fs from ‘file-saver‘; downloadDocument() { this.httpClient.get(‘yourUrl‘,{observe: ‘response‘,responseType: ‘blob‘}).subscribe(response => { fs.saveAs(response.body,this.getFilename(response.headers)); }); } private getFilename(headers: httpHeaders): String { const disposition = headers.get(‘Content-Disposition‘); if (!disposition || disposition.indexOf(‘filename=‘) < 0) { return ‘‘; } return disposition.substr(disposition.indexOf(‘filename=‘) + 9); }
或
downloadDocument() { this.httpClient.get(‘yourUrl‘,{responseType: ‘blob‘}).subscribe(data => { fs.saveAs(data,‘yourFilename‘); }); }
@L_489_34@
Apache POI Word Tutorial
以上是大佬教程为你收集整理的Angular/Spring Boot Rest API下载Word文档全部内容,希望文章能够帮你解决Angular/Spring Boot Rest API下载Word文档所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。