Apache POI-02.入门案例-通过POI向Excel文件写入文件内容-通过POI读取Excel文件内容

发布于:2025-06-29 ⋅ 阅读:(16) ⋅ 点赞:(0)

一.入门案例

向excel文件中写入并读出 

package com.sky.test;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.*;

//@SpringBootTest
public class POITest {

    // 对Excel表进行操作  使用POITest创建对象时是在内存中,而不是在磁盘
    public static void write() throws Exception {
        XSSFWorkbook excel = new XSSFWorkbook();
        XSSFSheet sheet = excel.createSheet("info");      // 创建一个sheet      指定sheet信息
        XSSFRow row = sheet.createRow(1);       // 创建一行     POI操作excel表时索引是从0开始的
        XSSFCell cell = row.createCell(1);// 指定列,创建一个单元格
        cell.setCellValue("姓名");    // 设定单元格的值
        cell = row.createCell(2);// 指定列,创建一个单元格
        cell.setCellValue("城市");    // 设定单元格的值

        // 创建一个新行
        row = sheet.createRow(2);
        cell = row.createCell(1);
        cell.setCellValue("张三");
        cell = row.createCell(2);
        cell.setCellValue("北京");

        // 创建一个新行
        row = sheet.createRow(3);
        cell = row.createCell(1);
        cell.setCellValue("李斯");
        cell = row.createCell(2);
        cell.setCellValue("南京");

        // 通过输出流将内存中的Excel文件写入磁盘
        FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\info.xlsx"));
        excel.write(fileOutputStream);      // XSSFWorkbook调用write方法将输出流写出

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

    // 对Excel表进行操作  读取excel表中的内容到控制台
    public static void read() throws Exception {
        InputStream inputStream = new FileInputStream(new File("D:\\info.xlsx"));
        // 读取磁盘上已经存在的excel文件
        XSSFWorkbook excel = new XSSFWorkbook(inputStream);

        XSSFSheet sheet = excel.getSheet("info");
        // 获取表中有数据的最后一行     0开始
        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);
        }

        // 关闭资源
        excel.close();
        inputStream.close();
    }

    public static void main(String[] args) throws Exception{
//        write();
        read();
    }
}

写入excel表格中的内容为:

读取excel表格中的内容为:- 


网站公告

今日签到

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