java生成excel工具类,可创建多sheet

avatar
public static void createExcel(String folder, String fileName, Map<String, List<String>> heads, Map<Integer, List<List<String>>> data) {
    Workbook workbook = new XSSFWorkbook();
    int sheetNo = 0;
    for (Map.Entry<String, List<String>> headerEntry : heads.entrySet()) {
        Sheet sheet = workbook.createSheet(headerEntry.getKey());
        List<String> headerList = headerEntry.getValue();
        Row row = sheet.createRow(0);
        for (int i = 0; i < headerList.size(); i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(headerList.get(i));
        }

        if (sheetNo < data.size()) {
            List<List<String>> sheetData = data.get(sheetNo);
            for (int i = 0; i < sheetData.size(); i++) {
                row = sheet.createRow((i + 1));
                List<String> rowData = sheetData.get(i);
                for (int j = 0; j < rowData.size(); j++) {
                    Cell cell = row.createCell(j);
                    cell.setCellValue(rowData.get(j));
                }
            }
        }
        sheetNo++;
    }

    // 生成excel文件
    String savePath = folder + File.separator + fileName + ".xlsx";
    try {
        FileOutputStream fileout = new FileOutputStream(savePath);
        workbook.write(fileout);
        fileout.flush();
        fileout.close();
    } catch (IOException e) {
        logger.info(e.getMessage());
    }
}
0 条评论

目前还没有回答,快来帮帮TA吧!

添加一条评论 请尽量发布对他人有帮助的评论

登录后可发布评论

登录 | Github登录