Excel工作表的读或写

第一步导入jar包

<!--POI报表-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>${poi.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>${poi.version}</version>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>${jedis.version}</version>
</dependency>

第二部测试文件的读或写

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class POITest {

    //使用 poi  读取 excel 文件中的数据
    @Test
    public void testRead() throws Exception {
        //第一步 使用流 读取文件
        FileInputStream fileInputStream =
                new FileInputStream(new File("Excel文件全路径"));
        //2.使用 xssf 去创建 我们 workbook
        XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);
        //3.获取sheet 根据索引
        XSSFSheet sheet = excel.getSheetAt(0);
        //获取行数据
        for (Row row : sheet) {
            System.out.println(row);
            //获取单元格数据
            for (Cell cell : row) {
                System.out.println(cell.getStringCellValue());
            }
        }
        //关闭
        excel.close();
    }

    //使用poi写入到磁盘
    @Test
    public void  testWriteExcel() throws IOException {
        //1.创建 excel 对象
        XSSFWorkbook excel = new XSSFWorkbook();
        //2.创建sheet
        XSSFSheet sheet = excel.createSheet("xxx");
        //3. row   cell
        XSSFRow title = sheet.createRow(0);
        //cell
        title.createCell(0).setCellValue("姓名");
        title.createCell(1).setCellValue("年龄");
        title.createCell(2).setCellValue("地址");
        //内容
        XSSFRow dataRow = sheet.createRow(1);
        dataRow.createCell(0).setCellValue("张三");
        dataRow.createCell(1).setCellValue("男");
        dataRow.createCell(2).setCellValue("北京");

        //创建excel 存入内容
        FileOutputStream outputStream =
                new FileOutputStream(new File("Excel文件全路径"));
       	//写入数据
        excel.write(outputStream);
        //刷新
        outputStream.flush();
        //关闭
        excel.close();
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

trysoharder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值