Excel 文件读取

package com.jiaofb.day09;

import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
/**
 * @Auther: iteration.0
 * @Date: 13/4/2021 - 04 - 13 - 12:59 PM
 * @Description: 第一题:
 * 使用两种方式读取exam.xls(从附件中下载)中所有的数据。
 * @version: 1.0
 */
public class TestExcel {
    public static void main(String[] args) {
        /**
         * 1.创建输入流,读取excel文件
         * 2.调用POI   API 创建Excel 对象
         * 3.获取sheet
         * 4.获取所有行
         * 5.获取所有单元格
         */
        try {
            //1.创建输入流,读取excel文件
            FileInputStream  fis=new FileInputStream("src\\test\\resources\\exam.xls");
             //2.调用POI   API 创建Excel 对象
           Workbook sheets= WorkbookFactory.create(fis);
           //关闭流
            fis.close();
            //3.获取sheet
            Sheet sheet= sheets.getSheet("用例");
            //4.获取所有行
            System.out.println("增强for 循环遍历:");
            for (Row row:sheet){
                if(row.getRowNum()==0)
                    continue;
                //5.获取所有单元格
                for(Cell cell:  row){
                    //把所有单元格cell 都转成String
                    //枚举:可穷举,作用:防止输入错误的参数
                    cell.setCellType(CellType.STRING);
                    System.out.print(cell.getStringCellValue()+"    ");
                }
                System.out.println();
            }
            System.out.println("普通for 循环遍历:");
           int  lastRowNum=sheet.getLastRowNum();
            for (int i = 1; i <= lastRowNum; i++) {
                Row  row=sheet.getRow(i);
                int   lastCellNum=row.getLastCellNum();
                for (int j = 0; j <= lastCellNum; j++) {
                    //Row.MissingCellPolicy.CREATE_NULL_AS_BLANK   防止返回的cell is null
                    //如果是null    new  一个空的cell  返回
                    //Cell cell=row.getCell(j);
                    Cell cell=row.getCell(j,Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                    cell.setCellType(CellType.STRING);
                    System.out.print(cell.getStringCellValue()+"   ");

                }
                System.out.println();
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

}

Ps:

第一步pom.xml 中配置依赖

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.0.0</version>
</dependency>

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值