springboot+vue+element-ui下載excel模板(靜態文件)

前端: 

html:
      <div style="margin-top: 20px">
        <el-button  @click="downloadDemo" size="small">下載模板</el-button>
      </div>

js:


      downloadDemo () {
        let url = Config.context + '/userManager/downloadExcel'
        this.common.exportData(url, this.queryForm, '數據模板_' + this.common.getTime())
      }
  exportData (url, data, fileName) {
    axios({
      method: 'POST',
      url: url,
      data: data,
      responseType: 'blob'
    }).then(response => {
      if (!response) {
        return
      }
      const blob = new Blob([response.data])
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName)
      } else {
        let u = window.URL.createObjectURL(response.data)
        let aLink = document.createElement('a')
        aLink.style.display = 'none'
        aLink.href = u
        aLink.setAttribute('download', fileName + '.xlsx')
        document.body.appendChild(aLink)
        aLink.click()
        document.body.removeChild(aLink)
        window.URL.revokeObjectURL(u)
      }
    }).catch(error => {
      throw error
    })
  }

 

後端:

controller層:

    @RequestMapping("/downloadExcel")
    public ResponseEntity<byte[]> download2() throws IOException {
        File file = excelModelService.buildXlsById();
        return FileUtils.buildResponseEntity(file);
    }

service層:

import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;

@Service
public class ExcelModelService {
    public File buildXlsById(){
        //do something to find this file
        File file=null;
        try {
            file = ResourceUtils.getFile("classpath:templates/model.xlsx");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return file;
    }
}

這裏寫的是靜態文件的存放路徑,注意不能中文名不然識別不了

文件下載工具類:

    public static ResponseEntity<byte[]> buildResponseEntity(File file) throws IOException {
        byte[] body = null;
        //獲取文件
        InputStream is = new FileInputStream(file);
        body = new byte[is.available()];
        is.read(body);
        HttpHeaders headers = new HttpHeaders();
        //設置文件類型
        headers.add("Content-Disposition", "attchement;filename=" + file.getName());
        //設置Http狀態碼
        HttpStatus statusCode = HttpStatus.OK;
        //返回數據
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        return entity;
    }

後續補充:

  以上方式實現在開發環境沒有任何問題,但是在生產環境會出現無法下載後臺報錯的情況,原因在於用流的方式讀取文件,打成jar包之後,下載的文件會被損壞 ,後來網上說配置pom裏面文件路徑等等試了沒用,直接用了POI的導出

修改後controller:

   @RequestMapping(value="/downloadExcel")
    public ResponseEntity<Resource> excel2007Export(HttpServletResponse response, HttpServletRequest request) {
        try {
            ClassPathResource cpr = new ClassPathResource("/templates/"+"model.xlsx");
            InputStream is = cpr.getInputStream();
            Workbook workbook = new XSSFWorkbook(is);
            String fileName = "model.xlsx";
            downLoadExcel(fileName, response, workbook);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new ResponseEntity<Resource>(HttpStatus.OK);
    }

文件工具類downLoadExcel:

    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章