当前位置: 首页 > 工具软件 > Excel2Entity > 使用案例 >

导出Excel,HttpServletResponse和ResponseEntity<byte[]>两种方式

丰岳
2023-12-01
public void exportDictExcel(HttpServletRequest request, HttpServletResponse response,
                                @ApiParam(name = "keywordId",value = "特征词ID",required = true)@RequestParam("keywordId") String keywordId) throws IOException {
        String fileName = "FeatureWord.xlsx";
        String userAgent = request.getHeader("user-agent");
        if (userAgent != null && userAgent.indexOf("Edge") >= 0) {
            fileName = URLEncoder.encode(fileName, "UTF8");
        } else if (userAgent.indexOf("Firefox") >= 0 || userAgent.indexOf("Chrome") >= 0
                || userAgent.indexOf("Safari") >= 0) {
            fileName = new String((fileName).getBytes("UTF-8"), "ISO8859-1");
        } else {
            // 其他浏览器
            fileName = URLEncoder.encode(fileName, "UTF8");
        }

        List<String> list = featureDictExcelService.queryExportDictList(keywordId);
        if (org.apache.commons.collections.CollectionUtils.isEmpty(list)){
            return;
        }

        // 以流的形式下载文件。
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setCharacterEncoding("UTF-8");


        XSSFWorkbook wb = new XSSFWorkbook();
        OutputStream os = response.getOutputStream();
        try {
            XSSFSheet sheet = wb.createSheet("特征词词典");
            //设置默认行高,表示2个字符的高度,必须先设置列宽然后设置行高,不然列宽没有效果
            sheet.setDefaultRowHeight((short) (2 * 256));
            //设置默认列宽
            sheet.setDefaultColumnWidth(17);
            XSSFRow row = sheet.createRow(0);
            XSSFCell cell = row.createCell(0);
            cell.setCellValue("词名称");

            for (int i = 0; i < list.size(); i++) {
                XSSFRow xssfRow = sheet.createRow(i + 1);
                String dictName = list.get(i);
                XSSFCell xssfCell = xssfRow.createCell(0);
                xssfCell.setCellValue(dictName);
            }
            log.info("exportDictExcel -> start write...");
            wb.write(os);
            wb.close();
            os.close();
        } catch (Exception e){
            log.error("export error:{}",e);
        }
    }

 

public ResponseEntity<byte[]> exportDictExcel(@ApiParam(name = "keywordId",value = "特征词ID",required = true)@RequestParam("keywordId") String keywordId,
                                                  HttpServletRequest request, HttpServletResponse response){
        byte[] bytes = featureDictExcelService.exportDictExcel(keywordId);

        StringBuilder sb = new StringBuilder();
        sb.append("C:\\FeatureDict").append(DateUtils.getTimeStamp()).append(".xlsx");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", sb.toString());

        return new ResponseEntity<>(bytes, headers, HttpStatus.CREATED);
    }


public byte[] exportDictExcel(String keywordId) {
        LambdaQueryWrapper<SkillFeatureWordData> query = Wrappers.lambdaQuery();
        query.eq(SkillFeatureWordData::getFeatureWordId,keywordId);
        List<SkillFeatureWordData> entityList = skillFeatureWordDataService.list(query);
        if (CollectionUtils.isEmpty(entityList)){
            throw ExceptionEnum.EXPORT_NO_DATA.getException();
        }
        List<String> list = entityList.stream().map(SkillFeatureWordData::getWord).collect(Collectors.toList());

        XSSFWorkbook wb = new XSSFWorkbook();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try{

            if (org.apache.commons.collections.CollectionUtils.isEmpty(list)){
                wb.write(os);
                wb.close();
                byte[] body = os.toByteArray();
                os.close();
                return body;
            }
            XSSFSheet sheet = wb.createSheet("特征词词典");
            XSSFRow row = sheet.createRow(0);
            XSSFCell cell = row.createCell(0);
            cell.setCellValue("词名称");

            for(int i=0; i<list.size(); i++){
                XSSFRow xssfRow = sheet.createRow(i + 1);
                String dictName = list.get(i);
                XSSFCell xssfCell = xssfRow.createCell(0);
                xssfCell.setCellValue(dictName);
            }
            log.info("exportDictExcel -> start write...");
            wb.write(os);
            wb.close();
            byte[] body = os.toByteArray();
            os.close();
            return body;
        }catch (Exception e){
            log.error("error:",e);
        }finally {
            try {
                wb.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

如果自己的框架对整体做了拦截,可以使用第一种(HttpServletResponse)方式返回,如果没有框架层面的拦截,可以是用第二种(ResponseEntity)方式返回。

 

 

 类似资料: