簡體   English   中英

如何為具有 Excel 工作表文件的 InputStream 構建響應主體?

[英]How to construct the response body for InputStream which has an Excel sheet file?

我正在編寫一個獲取 API 來獲取存儲在 src/main/resources 中的 Excel 工作表文件。

InputStream 具有 excel 文件(xlsm 格式)的內容。 但響應是數據損壞。

@GetMapping("/downloadTemplate")
public ResponseEntity<?> downloadTemplate() throws IOException {
    String fn = "filename";

    try {
        File file = new File(getClass().getClassLoader().getResource(fn).getFile());
        InputStreamSource iss = new FileSystemResource(file);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename= SimpleStandardTemplate.xlsm")
                .body(IOUtils.toByteArray(iss.getInputStream()));
    } catch (Exception e) {
        log.error("An error occurred while trying to downloadTemplate: {}", e);
        throw new ApiException(ApiErrorCode.DEFAULT_410, "Error while downloading");
    }
}

似乎這一行有一個問題“body(IOUtils.toByteArray(iss.getInputStream()));” . 如果還有任何替代方法? 否則可能是什么問題?

編輯:我認為問題在於內容長度。

試試這個,用 spring-boot 1.5.6測試過

@GetMapping("/export")
  public ResponseEntity<Resource> download() throws IOException {
    String fileName ="<file-path>";
    Resource resource = new FileSystemResource(fileName);
    return ResponseEntity.ok()
        .contentType(MediaType.parseMediaType(MediaType.APPLICATION_OCTET_STREAM_VALUE))
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
        .body(resource);
  }

我認為您的 MIME 類型是錯誤的, 請參閱此用於 excel Mime 類型,我已更改您使用Spring's FileSystemResource發送文件的方式

@GetMapping(value = "/downloadTemplate", produces = "application/vnd.ms-excel.sheet.macroEnabled.12")
public FileSystemResource downloadTemplate(HttpServletResponse response) throws IOException {
    String fn = "filename";
    File file = new File(getClass().getClassLoader().getResource(fn).getFile()); 
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename= SimpleStandardTemplate.xlsm");
    return new FileSystemResource(file); // You could directly pass the absolute path of the file
}

一個潛在的問題是您的原始文件不是 xlsm 文件。 例如,Excel 不允許您在啟用宏的模式下打開普通的 xlsx 文件。 請仔細檢查。

這個答案解決了這個問題

將此插件添加到 pom.xml 文件中。

    <plugin>
      <artifactId>maven-resources-plugin</artifactId>
      <version>2.5</version>
      <configuration>
        <encoding>UTF-8</encoding>
        <nonFilteredFileExtensions>
           <nonFilteredFileExtension>xls</nonFilteredFileExtension>
        </nonFilteredFileExtensions>
      </configuration>
    </plugin>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM