SpringBoot向Excel模板中寫入資料並下載 (無需獲取file物件及模板絕對路徑)

2022-12-10 12:00:16

之前用獲取模板路徑的方式測試沒問題打包後就有問題了

莫名出現一個! 找了很多教學嘗試無果 最終使用下面這個方式
無需獲取file物件以及模板路徑的方式進行寫入下載
(那個設定瀏覽器編碼沒有測試不知道能不能用!!!)

 public void export(SampleFilterAO filter, HttpServletResponse response, HttpServletRequest request) {

        Map<String, Object> map = new HashMap<>();
        // 獲取匯出的時間引數
        String date = request.getParameter("Date");
        map.put("Date", date);
        String fileName = "data.xlsx";
        // 使用類載入器獲取excel檔案流,基於模板填充資料
        ClassPathResource classPathResource = new ClassPathResource(fileName);
        InputStream is = null;
        XSSFWorkbook workbook = null;
        try {
            is = classPathResource.getInputStream();
            workbook = new XSSFWorkbook(is);
            XSSFSheet sheet = null;
            // 獲取第一個sheet頁
            // getSheet的引數是sheet的名稱, 獲取具體名稱的sheet。
            sheet = workbook.getSheetAt(0);
            Long offset = (filter.getPage() - 1) * filter.getLimit();
            filter.setOffset(offset);
            filter.setLimit(sampleMapper.count(filter).intValue());
            List<Sample> resutList = sampleMapper.list(filter);
            for (int i = 0; i < resutList.size(); i++) {
                Integer j=i+1;
                writeExcel(sheet, resutList, j, i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //檔案下載
        response.reset();
        response.setContentType("text/html;charset=UTF-8");
        response.setContentType("application/x-msdownload");
        String newName = "";
        try {
            newName = URLEncoder.encode("掃描記錄匯出" + System.currentTimeMillis() + ".xlsx", "UTF-8");
            String s = encodeFileName(request,newName);
            response.addHeader("Content-Disposition", "attachment;filename=\"" + s + "\"");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            workbook.write(toClient);
            toClient.flush();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
	//寫入資料的方法
    public void writeExcel(XSSFSheet sheet, List<Sample> resutList,Integer rownum, Integer index) {
        if (resutList.get(index) != null && !"".equals(resutList.get(index))) {
            Row row = sheet.createRow(rownum);

            Cell cell = row.createCell(0); //序號
            cell.setCellValue(index+1);

            String sampleNo = resutList.get(index).getSampleNo();// 玻片編號
            cell = row.createCell(1);
            cell.setCellValue(sampleNo);

            String patientNo = resutList.get(index).getPatientNo();// 病案號
            cell = row.createCell(2);
            cell.setCellValue(patientNo);

            String patientName = resutList.get(index).getPatientName();// 姓名
            cell = row.createCell(3);
            cell.setCellValue(patientName);

            String patientSex = resutList.get(index).getPatientSex();// 性別
            cell = row.createCell(4);
            cell.setCellValue(patientSex);

            String position = resutList.get(index).getPosition();// 部位
            cell = row.createCell(5);
            cell.setCellValue(position);

            String aiResultId = resutList.get(index).getAiResultId();// AI檢驗結果
            cell = row.createCell(6);
            cell.setCellValue(aiResultId);

            String createdName = resutList.get(index).getCreatedName();// 掃描人員
            cell = row.createCell(7);
            cell.setCellValue(createdName);

            Long createdAt = resutList.get(index).getCreatedAt();// 記錄時間
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = format.format(createdAt);
            cell = row.createCell(8);
            cell.setCellValue(time);
        }
    }
	//不同瀏覽器設定不同編碼(未測試!)
    public static String encodeFileName(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException {

        String newFilename = URLEncoder.encode(fileName, "UTF8").replaceAll("\\+", "%20");

        String agent = request.getHeader("USER-AGENT").toLowerCase();
        if (null != agent && -1 != agent.indexOf("msie")) {
            /**
             * IE瀏覽器,只能採用URLEncoder編碼
             */
            return newFilename;
        } else if (null != agent && -1 != agent.indexOf("applewebkit")) {
            /**
             * Chrome瀏覽器,只能採用ISO編碼的中文輸出
             */
            return new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        } else if (null != agent && -1 != agent.indexOf("opera")) {
            /**
             * Opera瀏覽器只可以使用filename*的中文輸出
             * RFC2231規定的標準
             */
            return newFilename;
        } else if (null != agent && -1 != agent.indexOf("safari")) {
            /**
             * Safani瀏覽器,只能採用iso編碼的中文輸出
             */
            return new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        } else if (null != agent && -1 != agent.indexOf("firefox")) {
            /**
             * Firfox瀏覽器,可以使用filename*的中文輸出
             * RFC2231規定的標準
             */
            return newFilename;
        } else {
            return newFilename;
        }
    }

本文轉自:https://blog.csdn.net/wongrock/article/details/118359816