Angular/Spring Boot Rest API下载Word文档
2020-12-13 03:04
标签:更新 https package gis ret replace methods 替换 scribe 使用POI XWPF生成Word文档,引入POI: 项目中经常从Word模板生成文档,下面示例演示了替换文档内容的方法。模版中要替换的内容以${}标识,调用XWPFRun.setText()方法更新文档。 调用replaceDocument()方法生成word文档,如要在Rest API中定义文件名称,使用ResponseEntity并增加header,否则可以直接返回byte[]。 配置CORS的ExposedHeaders,否则前台不能读取"Content-Disposition": 可以使用链接直接访问REST URL下载文档,若项目启用了JWT Token验证,则必须使用HttpClient的get方法。 然后在tsconfig.json中添加: 下载方法: 或 Excel File – Download from SpringBoot RestAPI + Apache POI + MySQL Angular/Spring Boot Rest API下载Word文档 标签:更新 https package gis ret replace methods 替换 scribe 原文地址:https://blog.51cto.com/7308310/2412183package 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
Spring Boot Rest API
@GetMapping("/api/doc/{heroName}")
public ResponseEntity
@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;
}
Angular下载文档
本文使用了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=‘)
downloadDocument() {
this.httpClient.get(‘yourUrl‘, {responseType: ‘blob‘}).subscribe(data => {
fs.saveAs(data, ‘yourFilename‘);
});
}
参考文档
Apache POI Word Tutorial
文章标题:Angular/Spring Boot Rest API下载Word文档
文章链接:http://soscw.com/essay/26871.html