Excel表的写与读

导出

@Test
    public void test() throws IOException {
        //创建一个工作簿
        Workbook w = new HSSFWorkbook();
        //创建一个工作表
        Sheet s = w.createSheet("这是第一个工作表");
        for (int i = 0;i < 10;i++){
            //设置第 i 行
            Row r1 = s.createRow(i);
            //设置第 i 行的第一列
            Cell c1 = r1.createCell(0);
            //给第一列设置值
            c1.setCellValue("x1");
            //设置第 i 行的第二列
            Cell c2 = r1.createCell(1);
            //给第二列设置值
            c2.setCellValue("x2");
            Cell c3 = r1.createCell(2);
            c3.setCellValue("x3");
        }
        //判断xlsx文件是否存在
        String path = "D:/b.xlsx";
        File file = new File(path);
        if(file.exists()){
            file.delete();
        }
        //查看父级目录是否存在
        File parentFile = file.getParentFile();
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }
        //创建文件
        file.createNewFile();
        //生成一张表到指定路径  IO
        FileOutputStream stream = new FileOutputStream(path);
        w.write(stream);
        w.close();
    }

请看结果:

读入

String path = "D:/b.xlsx";
        FileInputStream inputStream = new FileInputStream(path);
        //读取Excel表
        Workbook workbook = new HSSFWorkbook(inputStream);
        //获取第一个sheet表
        Sheet sheetAt = workbook.getSheetAt(0);
        //获取第一行
        Row row = sheetAt.getRow(0);
        //获取第一行第一列
        Cell cell = row.getCell(0);
        System.out.println(cell);
        inputStream.close();

效果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值