使用POI XWPF生成Word文檔,引入POI:
創(chuàng)新互聯(lián)專注于企業(yè)成都營銷網(wǎng)站建設(shè)、網(wǎng)站重做改版、承德縣網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、H5響應(yīng)式網(wǎng)站、商城網(wǎng)站建設(shè)、集團(tuán)公司官網(wǎng)建設(shè)、外貿(mào)營銷網(wǎng)站建設(shè)、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計(jì)等建站業(yè)務(wù),價(jià)格優(yōu)惠性價(jià)比高,為承德縣等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
項(xiàng)目中經(jīng)常從Word模板生成文檔,下面示例演示了替換文檔內(nèi)容的方法。模版中要替換的內(nèi)容以${}標(biāo)識,調(diào)用XWPFRun.setText()方法更新文檔。
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;
public final class XWPFDocumentUtils {
private 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()) {
if (!paragraph.getText().contains("${")) {
continue;
}
replaceParagraph(paragraph, fields);
}
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
doc.write(out);
return out.toByteArray();
}
}
}
private static void replaceParagraph(XWPFParagraph paragraph, Map<String, String> fields) {
for (Map.Entry<String, String> field : fields.entrySet()) {
String find = "${" + field.getKey() + "}";
if (!paragraph.getText().contains(find)) {
continue;
}
replaceText(paragraph, find, field.getValue());
}
}
private static void replaceText(XWPFParagraph paragraph, String key, String value) {
List<XWPFRun> runs = paragraph.getRuns();
for (int i = 0; i < runs.size(); i++) {
XWPFRun run = runs.get(i);
String text = run.text();
if (text.contains("${") || (text.contains("$") && runs.get(i + 1).text().startsWith("{"))) {
StringBuilder builder = new StringBuilder(text);
while (!text.contains("}")) {
text = runs.get(i + 1).text();
builder.append(text);
paragraph.removeRun(i + 1);
}
text = builder.toString();
run.setText(text.contains(key) ? text.replace(key, value) : text, 0);
}
}
}
}
調(diào)用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,否則前臺(tái)不能讀取"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;
}
測試使用exchange方法,設(shè)置header APPLICATION_OCTET_STREAM:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HeroesApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void getDocumentSuccess() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<byte[]> response = restTemplate.exchange("/api/doc/jason", HttpMethod.GET, entity, byte[].class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}
可以使用鏈接直接訪問REST URL下載文檔,若項(xiàng)目啟用了JWT Token驗(yàn)證,則必須使用HttpClient的get方法。
本文使用了FileSaver.js保存文檔,開始之前先安裝:
npm install --save file-saver
然后在tsconfig.json中添加:
"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');
});
}
Excel File – Download from SpringBoot RestAPI + Apache POI + MySQL
Apache POI Word Tutorial
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
網(wǎng)站題目:Angular/SpringBootRestAPI下載Word文檔-創(chuàng)新互聯(lián)
URL地址:http://jinyejixie.com/article24/ccsgce.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、云服務(wù)器、響應(yīng)式網(wǎng)站、軟件開發(fā)、自適應(yīng)網(wǎng)站、外貿(mào)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容