Apache POI

发布于:2025-02-10 ⋅ 阅读:(54) ⋅ 点赞:(0)

依赖

<properties>  
 <poi>3.16</poi>
</properties>
 <!-- poi -->
  <dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi</artifactId>
     <version>${poi}</version>
  </dependency>
  <dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi-ooxml</artifactId>
     <version>${poi}</version>
  </dependency>

基础写入

        //在内存中创建一个Excel文件
        XSSFWorkbook excel = new XSSFWorkbook();

        //创建新的 sheet 页
        XSSFSheet sheet=excel.createSheet("info");

        //在sheet中创建  行对象  rownum从0开始
        XSSFRow row=sheet.createRow(0);
        
        //创建单元格对象
        XSSFCell cell=row.createCell(1);
        
        //单元格写入文件内容
        cell.setCellValue("姓名");
        row.createCell(2).setCellValue("城市");

        FileOutputStream fileOutputStream=new FileOutputStream(new File("D:\\info.xlsx"));
        excel.write(fileOutputStream);

        //关闭资源
        fileOutputStream.close();
        excel.close();

基础读取

 //读取磁盘上已经存在的 Excel 文件
        InputStream in=new FileInputStream(new File("D:\\info.xlsx"));
        XSSFWorkbook excel = new XSSFWorkbook(in);

        //获取页对象
        XSSFSheet sheet=excel.getSheetAt(0);       //根据下标获取
        XSSFSheet sheet2=excel.getSheet("info");   //根据名字获取

        //获取Sheet中最后一行的行号
        int lastRowNum=sheet.getLastRowNum();

        for (int i=1;i<lastRowNum;i++){
            //获取行对象
            XSSFRow row=sheet.getRow(i);

            //获取单元格
            String cellValue1=row.getCell(1).getStringCellValue();
            String cellValue2=row.getCell(2).getStringCellValue();

            System.out.println(cellValue1+" "+cellValue2);
        }
        in.close();
        excel.close();

网站公告

今日签到

点亮在社区的每一天
去签到