【工具類】Excel導出那些事兒(四)

      Excel的導出需求層出不窮,,之前都是直接導出list<T>,或者導出List<map>,現在需要導出雙標題Excel。使用poi實現.本篇先介紹基礎的導出方法

引用的jar包

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>3.17</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.17</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-excelant</artifactId>
    <version>3.17</version>
</dependency>

首先是基礎用法(單表頭導出)

//要導出的數據
List<T> list;
String[] tempTitle = {"第一列","第二列","第三列","第四列"};
List<String> tempList= Arrays.asList(tempTitle);
List<String> titleList = new ArrayList<>();
titleList.addAll(tempList);
//動態字段
List<String> collectTitle = list.get(0).getList().stream().map(ResultVo::getName).collect(Collectors.toList());
List<String> 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<ResultVo> 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;
}

 

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