0
点赞
收藏
分享

微信扫一扫

将Map集合中的数据导入到Excel中

需求:

输入两个Map集合,分别将两个Map集合中的key和value对应显示在excel的对应的页面上

代码:

<!-- Apache POI 依赖 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.2.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.4</version>
        </dependency>

public static void writeStatisticsToExcel(HashMap<String, Integer> ipMap, HashMap<String, Integer> linkMap, String outputPath, String fileName) {
    try (Workbook workbook = new XSSFWorkbook()) {
        // 创建两个不同的工作表
        Sheet ipSheet = workbook.createSheet("IP Statistics");
        Sheet linkSheet = workbook.createSheet("URL Statistics");
 
        // 写入 IP 统计信息到 IP Sheet
        int ipRowCount = 0;
        //创建了一个行对象ipRow
        Row ipRow = ipSheet.createRow(ipRowCount++);
        //第一个单元格(列索引为0)写入了"IP
        ipRow.createCell(0).setCellValue("IP");
        //在第二个单元格(列索引为1)写入了"Count
        ipRow.createCell(1).setCellValue("Count");
 
        //对于ipMap中的每个条目,都创建了新的行对象,并在第一个单元格中写入IP地址(Map中的Key),在第二个单元格中写入对应的计数值(Map中的Value)
        for (Map.Entry<String, Integer> entry : ipMap.entrySet()) {
            ipRow = ipSheet.createRow(ipRowCount++);
            ipRow.createCell(0).setCellValue(entry.getKey());
            ipRow.createCell(1).setCellValue(entry.getValue());
        }
 
        //与上面相同的逻辑
        //写入链接统计信息到链接 Sheet
        int linkRowCount = 0;
        Row linkRow = linkSheet.createRow(linkRowCount++);
        linkRow.createCell(0).setCellValue("URL");
        linkRow.createCell(1).setCellValue("Count");
 
        for (Map.Entry<String, Integer> entry : linkMap.entrySet()) {
            linkRow = linkSheet.createRow(linkRowCount++);
            linkRow.createCell(0).setCellValue(entry.getKey());
            linkRow.createCell(1).setCellValue(entry.getValue());
        }
 
        // 保存 Excel 文件
        String excelFilePath = outputPath + File.separator + fileName.replace(".json", ".xlsx");
        try (FileOutputStream outputStream = new FileOutputStream(excelFilePath)) {
            workbook.write(outputStream);
        }
 
        System.out.println("Excel file for " + fileName + " written successfully!");
 
    } catch (IOException e) {
        e.printStackTrace();
    }
}

举报

相关推荐

0 条评论