【工具类】Excel导出那些事儿(四)

      Excel的导出需求层出不穷,,之前都是直接导出list,或者导出List,现在需要导出双标题Excel。使用poi实现.本篇先介绍基础的导出方法

引用的jar包


    org.apache.poi
    poi
    3.17



    org.apache.poi
    poi-scratchpad
    3.17


    org.apache.poi
    poi-ooxml
    3.17


    org.apache.poi
    poi-ooxml-schemas
    3.17


    org.apache.poi
    poi-excelant
    3.17

首先是基础用法(单表头导出)

//要导出的数据
List list;
String[] tempTitle = {"第一列","第二列","第三列","第四列"};
List tempList= Arrays.asList(tempTitle);
List titleList = new ArrayList<>();
titleList.addAll(tempList);
//动态字段
List collectTitle = list.get(0).getList().stream().map(ResultVo::getName).collect(Collectors.toList());
List titleTempList = new ArrayList<>();
collectTitle.forEach(item -> {
    titleTempList.add("返回字段(" + item + ")");
});
titleList.addAll(titleTempList);
String[] title = titleList.toArray(new String[]{});

String fileName = "数据导出_"  + DateUtils.formatDate(new Date()) + ".xlsx";
String sheetName = "Sheet明细";

try {
    String[][] content = new String[list.size()][];
    for (int i = 0; i < list.size(); i++) {
        content[i] = new String[title.length];
        DownExcelVo dto = list.get(i);
        //第一列
        content[i][0] = dto.getNo();
        //第二列
        content[i][1] = (dto.getIsSuccess().equals(1) ? "成功" :"失败");
        //第三列
        content[i][2] = String.valueOf(dto.getTime());
        //第四列
        content[i][3] = (dto.getCreateTime() != null) ? DateUtils.formatDate(dto.getCreateTime()) : "";
        //动态字段列
        List dictList = dto.getList();
        if(CollectionUtils.isNotEmpty(list) && CollectionUtils.isNotEmpty(dictList)){
            for(int j = 0;j < dictList.size();j++){
                ResultVo resultVo = dictList.get(j);
                content[i][j + 4] = resultVo.getValue() + "," + (resultVo.getValueStatus().equals(1) ? "正常值" :"异常值");
            }
        }

    }
    ExcelUtils.export(response, fileName, sheetName, title, content);
} catch (Exception ex) {
    logger.error("导出数据失败", ex);
    throw new RuntimeException(CodeMsgEnum.SYSTEM_PUBLIC_ERROR_APPKEY.getCode());
}

工具类方法如下:

public static void export(HttpServletResponse response, String fileName, String sheetName, String[] title, String[][] content) {
    XSSFWorkbook wb = new XSSFWorkbook();
    OutputStream os = null;
    try {
        wb = exportXls(sheetName, title, content, wb);
        setResponse(response, fileName);
        os = response.getOutputStream();
        wb.write(os);
        os.flush();
    } catch (Exception e) {
        LOGGER.error("io error");
    } finally {
        try {
            wb.close();
            if (os != null) {
                os.close();
            }
        } catch (Exception e) {
            LOGGER.error("close io error");
        }
    }
}

/**
 * 发送响应流方法
 */
public static void setResponse(HttpServletResponse response, String fileName) {
    try {
        fileName = new String(fileName.getBytes(), "ISO8859-1");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);


        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
    } catch (Exception ex) {
        LOGGER.info("error response head");
    }
}

/**
 * 导出Excel
 *
 * @param sheetName sheet名称
 * @param title     标题
 * @param values    内容
 * @param wb        HSSFWorkbook对象
 * @return
 */
public static XSSFWorkbook exportXls(String sheetName, String[] title, String[][] values, XSSFWorkbook wb) {

    // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
    if (wb == null) {
        wb = new XSSFWorkbook();
    }

    // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
    XSSFSheet sheet = wb.createSheet(sheetName);

    // 第四步,创建单元格,并设置值表头 设置表头居中
    XSSFCellStyle style = wb.createCellStyle();
    // 创建一个居中格式
    style.setAlignment(HorizontalAlignment.CENTER);


    // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
    XSSFRow row = sheet.createRow(0);
    XSSFCell cell;
    //创建标题
    for (int i = 0; i < title.length; i++) {
        cell = row.createCell(i);
        cell.setCellValue(title[i]);
        cell.setCellStyle(style);
    }

    //创建内容
    for (int i = 0; i < values.length; i++) {
        row = sheet.createRow(i + 1);
        for (int j = 0; j < values[i].length; j++) {
            //将内容按顺序赋给对应的列对象
            cell = row.createCell(j);
            cell.setCellStyle(style);
            cell.setCellValue(values[i][j]);
        }
    }
    return wb;
}

 

你可能感兴趣的:(Java,excel,poi,导出)