POI使用初体验

①导入相关maven地址②使用单元测试功能进行测试

1. 创建Excel表格

​
@Test
public void write() throws Exception {
    String file = "D:\\info.xlsx";
    //创建excel表格
    XSSFWorkbook excel  = new XSSFWorkbook();
   XSSFSheet sheet =  excel.createSheet("Sheet1");
   //创建行
    XSSFRow row = sheet.createRow(0);
    //创建单元格,并给单元格赋值
    XSSFCell cell1 = row.createCell(0);
    cell1.setCellValue("姓名");
    XSSFCell cell2 = row.createCell(1);
    cell2.setCellValue("年龄");
    XSSFCell cell3 = row.createCell(2);
    cell3.setCellValue("城市");
    //通过输出流,将内存中的excel存入到磁盘中
    FileOutputStream out = new FileOutputStream(new File(file));
    excel.write(out);
    //关闭资源
    excel.close();
    out.close();
}

​

创建成功

2. 读取Excel表格

@Test
    public void read() throws Exception {
        //将磁盘的Excel读取到内存中,使用XSSFWorkbook的有参构造器,传入输入流
        FileInputStream in = new FileInputStream(new File("D:\\info.xlsx"));
        XSSFWorkbook excel = new XSSFWorkbook(in);
        //获取Sheet1标签页的内容
        XSSFSheet sheet = excel.getSheet("Sheet1");
        //获取有文字的第一行和最后一行
        int start = sheet.getFirstRowNum();
        int end = sheet.getLastRowNum();
        //输出Excel的文字
        for(int i = start; i <= end;i++){
            XSSFRow row = sheet.getRow(i);
            String cell1 = row.getCell(0).getStringCellValue();
            String cell2 = row.getCell(1).getStringCellValue();
            String cell3 = row.getCell(2).getStringCellValue();
            System.out.println(cell1 + " " + cell2 + " " + cell3);
        }
        //关闭流
        in.close();
        excel.close();
    }

        最后输出

总结:一定要写write函数中excel.write(out),不然excel能成功写入磁盘,但是不能正常打开。

注意最后关闭流

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值