EasyExcel 多sheet页导出

2024-11-06  本文已影响0人  King斌
 public void export() {
            Workbook workbook = new XSSFWorkbook();
            // 查询数据data 导出标头信息可以用as转换成中文名称
            exportToExcelSheet(workbook,data,"sheet名称");
            // 多次调用 exportToExcelSheet
        // 将工作簿写入文件
        try (FileOutputStream fileOut = new FileOutputStream("D://WorkBook.xlsx")) {
            workbook.write(fileOut);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭工作簿
        try {
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

/**
 * 组装sheet页数据
**/ 
public static void exportToExcelSheet(Workbook workbook, List<JSONObject> data, String sheetName) {
        
        Sheet sheet = workbook.createSheet(sheetName);
        // 如果数据不为空
        if (!data.isEmpty()) {
            // 获取第一个JSON对象的所有键,作为表头
            JSONObject firstObject = data.get(0);
            Row headerRow = sheet.createRow(0);
            int columnCount = 0;
            for (String key : firstObject.keySet()) {
                Cell cell = headerRow.createCell(columnCount++);
                cell.setCellValue(key);
            }
            // 遍历数据列表,为每行数据创建一行
            int rowCount = 1;
            for (JSONObject jsonObject : data) {
                Row row = sheet.createRow(rowCount++);
                columnCount = 0;
                for (String key : firstObject.keySet()) { // 使用相同的键顺序
                    Cell cell = row.createCell(columnCount++);
                    cell.setCellValue(jsonObject.getStr(key, ""));
                }
            }
        }


    }
上一篇 下一篇

猜你喜欢

热点阅读