1. 程式人生 > >最簡單的EXCEL模板檔案下載

最簡單的EXCEL模板檔案下載

之前所用的下載檔案方法總是出現下載檔案未知大小的問題,百思不得其解,最後使用該方法後,問題解決。

  // 根目錄為resources
  private static final String filePath = "/excel/xxx.xlsx";
   /**
     * 下載EXCEL模板檔案
     * 
     * @param response
     */
    @ApiOperation(value = "下載EXCEL模板檔案", notes = "下載EXCEL模板檔案", httpMethod = "GET", produces = "application/vnd.ms-excel", protocols = "HTTP/1.1")
    @RequestMapping(value 
= "/download-excel-model", method = RequestMethod.GET) public void downloadImportTemplate(HttpServletResponse response) { try { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // 獲取所有匹配的檔案 org.springframework.core.io.Resource[] resources = resolver.getResources(filePath); InputStream stream
= resources[0].getInputStream(); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=xxx.xlsx"); IOUtils.copy(stream, response.getOutputStream()); response.flushBuffer(); } catch (IOException ex) { ex.printStackTrace(); } }

==============================================================================================================

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class DownloadExcelModel {

// 下載檔案路徑
private String filePath;

// 生成檔名稱
private String fileName;

public DownloadExcelModel() {

}

public DownloadExcelModel(String filePath, String fileName) {
this.filePath = filePath;
this.fileName = fileName;
}

/**
* <p>
* 通用Excel匯出方法,利用反射機制遍歷物件的所有欄位,將資料寫入Excel檔案中 <br>
* 此版本生成2007以上版本的檔案 (檔案字尾:xlsx)
* </p>
*/
public void downloadExcelModel(HttpServletResponse response) throws Exception {

ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// 獲取所有匹配的檔案
org.springframework.core.io.Resource[] resources = resolver.getResources(filePath);
InputStream inputStream = resources[0].getInputStream();

// response緩衝區重置
response.reset();
// 支援下載引數
response.setContentType("application/vnd.ms-excel");
// 設定瀏覽器響應頭對應的Content-disposition
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), StandardCharsets.ISO_8859_1) + ".xlsx");
// 設定響應編碼
response.setCharacterEncoding("UTF-8");

IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
}

}