1. 程式人生 > >項目加載excel模版文件遇到的坑

項目加載excel模版文件遇到的坑

exce 模版 oot pri 模版文件 填充 docker 重新 必須

  最近項目中有個需求:先加載excel模版文件,然後填充數據再下載。模版文件是提前做好的,首先想到是放在服務器的硬盤上,

通過 new File("/xxx/xxxx.xls") 這種方式就可以拿到。但是項目用的是docker ,每次服務重啟構建都要重新上傳,太麻煩。所以還是放到項目裏面比較方便,項目用的springboot,靜態文件放到resource目錄下面。

技術分享圖片

通過這種方式拿到文件: File file = new File(this.getClass().getClassLoader().getResource("template/export.xls").getFile());

本地測試ok ,但是到了服務上 報錯:file not found。

什麽情況?方式不對?ok 我換一種方式讀取

  ClassPathResource classPathResource = new ClassPathResource("template/export.xls");

  File file = classPathResource.getFile();

本地測試ok,服務器還是報錯:file not found。

經研究發現,服務器上是jar包,訪問裏面到靜態文件必須要通過流到方式讀取文件。

所以要用這種方式讀取文件:

  ClassPathResource classPathResource = new ClassPathResource("template/export.xls");
  InputStream initialStream = classPathResource.getInputStream();

 

項目加載excel模版文件遇到的坑