Apache POI学习 -2025/3/27

简介

使用

  1. 导入Apache poi的坐标

入门案例

public static void write() throws Exception{
        // 在内存中创建一个Excel文件
        XSSFWorkbook excel = new XSSFWorkbook();
        // 创建一个工作表
        XSSFSheet sheet = excel.createSheet("first");
        // 创建第一行
        XSSFRow row = sheet.createRow(0);
        // 创建第一行的第一列
        XSSFCell cell = row.createCell(0);
        // 设置第一列的值为"姓名"
        cell.setCellValue("姓名");

        cell = row.createCell(1);
        cell.setCellValue("性别");
        // 创建第二行,并设置值
        row = sheet.createRow(1);
        row.createCell(0).setCellValue("张三");
        row.createCell(1).setCellValue("男");
        // 创建第三行,并设置值
        row = sheet.createRow(2);
        row.createCell(0).setCellValue("李四");
        row.createCell(1).setCellValue("女");

        FileOutputStream fileOutputStream = new FileOutputStream("D://test.xlsx");
        excel.write(fileOutputStream);
        
        // 关闭资源
        fileOutputStream.close();
        excel.close();
    }

效果

public static void read() throws Exception{
        // 输入流
        FileInputStream fileInputStream = new FileInputStream("D://test.xlsx");
        XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);
        // 获取第一个工作表
        XSSFSheet sheet = excel.getSheetAt(0);
        // 获取最后一行的行号
        int lastRowNum = sheet.getLastRowNum();

        for(int i = 0; i <= lastRowNum; i++){
            XSSFRow row = sheet.getRow(i);
            String cellValue1 = row.getCell(0).getStringCellValue();
            String cellValue2 = row.getCell(1).getStringCellValue();
            System.out.println(cellValue1 + " " + cellValue2);
        }

        // 关闭资源
        fileInputStream.close();
        excel.close();
    }
posted @ 2025-03-27 22:56  XYu1230  阅读(27)  评论(0)    收藏  举报