SpringBoot向Excel模板中写入数据并下载 (无需获取file对象及模板绝对路径)

之前用获取模板路径的方式测试没问题打包后就有问题了
image
莫名出现一个! 找了很多教程尝试无果 最终使用下面这个方式
无需获取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();// 结果
            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

posted @ 2022-12-10 11:29  努力的小韩  阅读(447)  评论(0编辑  收藏  举报