Apache POI 操作excel

本文介绍了如何在SpringBoot项目中通过ApachePOI库实现Excel的读写功能,包括创建XSSFWorkbook对象、工作表操作、读取文件内容并打印数据。
摘要由CSDN通过智能技术生成

再springboot中需要使用java代码操作excel表格进行读写,可以使用Apache POI。

只需要导入maven坐标

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
    </dependency>

接下来只需写java

进行写操作时,先创建一个XSSFWorkbook对象,通过其创建工作表,在填写数据

进行读操作时,创建文件输入流,添加并把数据打印出来

public static void write() throws IOException {
        XSSFWorkbook excel = new XSSFWorkbook();
        XSSFSheet sheet = excel.createSheet("info");
        sheet.createRow(0).createCell(0).setCellValue("hello");
        FileOutputStream out = new FileOutputStream(new File("D:\\test.xlsx"));
        excel.write(out);
        out.close();
        excel.close();
    }
    public static void read() throws IOException {
        FileInputStream fileInputStream = new FileInputStream(new File("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);
            if (row != null) {
                //获取最后列号
                int lastCellNum = row.getLastCellNum();
                for (int j = 0; j < lastCellNum; j++) {
                    System.out.print(row.getCell(j)+"\t");
                }
                System.out.println();
            }
        }
        excel.close();
        fileInputStream.close();


    }

完成读写操作

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值