java基础入门-poi解析excel

前言: 在各种项目中,总是会遇到 生成excel的需求,于是 我们必须要掌握对excel的读写,所以我粗浅的认为这是java的入门基础

1.首先导包

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

        <!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.10</version>
        </dependency>
2.然后开始撸代码:用java在e盘创建一个如图的excel

   

   先看poi的写法


    public static void WriteExcel() throws Exception{
        String [] title={"id","name","age"};
        // 创建工作薄
        HSSFWorkbook hssfWorkbook=new HSSFWorkbook();
        // 创建要一个工作
        HSSFSheet sheet=hssfWorkbook.createSheet();
        //创建一行
        HSSFRow row=sheet.createRow(0);
        HSSFCell cell=null;// 每一小格
    这是 列头的名字
        for(int i=0; i<title.length;i++){
            cell=row.createCell(i);
            cell.setCellValue(title[i]);
        }

        // 追加数据
        for(int i=1;i<=6;i++){
            // 这是每一行  
            HSSFRow nextrow=sheet.createRow(i);
            HSSFCell cell1=nextrow.createCell(0);//第几列
            cell1.setCellValue("a"+1);
            cell1=nextrow.createCell(1);//第几列
            cell1.setCellValue("user");  值
            cell1=nextrow.createCell(2);
            cell1.setCellValue("23岁");
        }
        // 写入 流中
        File file=new File("e:/poi.xls");  
        FileOutputStream stream= FileUtils.openOutputStream(file);
        hssfWorkbook.write(stream);
        stream.close();
    }

********************读出excel中的数据*******

   

        File file=new File("e:/poi.xls");
        HSSFWorkbook workbook=new HSSFWorkbook(FileUtils.openInputStream(file));
        HSSFSheet sheet=workbook.getSheetAt(0);
        int fristRow=0;
        int laseRow=sheet.getLastRowNum();//最大行号
        for(int i=fristRow;i<=laseRow;i++){
            HSSFRow row=sheet.getRow(i);
            int lastcellnum=row.getLastCellNum();// 每一行的最大的列
            for(int j=0;j<lastcellnum;j++){
                HSSFCell cell=row.getCell(j);
                System.out.print(cell.getStringCellValue()+" ");
            }
            System.out.println("");
        }
3.

    归纳就是 :按照以下的顺序去写 去读就行

HSSFWorkBook--->    HSSFSheet--->  HSSFRow  ---> HSSFCell---》cellValue(内容) 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值