91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Angular/Spring Boot Rest API下載Word文檔

發布時間:2020-07-28 15:58:02 來源:網絡 閱讀:899 作者:川川Jason 欄目:軟件技術

POI生成Word文檔

使用POI XWPF生成Word文檔,引入POI:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.0</version>
</dependency>

項目中經常從Word模板生成文檔,下面示例演示了替換文檔內容的方法。模版中要替換的內容以${}標識,調用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);
            }
        }
    }
}

Spring Boot Rest API

Rest API

調用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

配置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;
}

Test

測試使用exchange方法,設置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);
    }
}

Angular下載文檔

可以使用鏈接直接訪問REST URL下載文檔,若項目啟用了JWT Token驗證,則必須使用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

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

荆州市| 清远市| 酉阳| 通辽市| 元氏县| 石泉县| 枣阳市| 桦川县| 建水县| 左权县| 扶风县| 高清| 屏南县| 新营市| 驻马店市| 那曲县| 军事| 连云港市| 罗甸县| 桂林市| 长葛市| 夹江县| 加查县| 合山市| 蒙自县| 婺源县| 韶山市| 胶南市| 永宁县| 屯昌县| 思南县| 新余市| 阜城县| 离岛区| 隆回县| 抚松县| 临高县| 阿拉善右旗| 崇明县| 八宿县| 南开区|