Apache POl初学

介绍

入门案例

通过POI写入操作

/**
 * 使用POI操作Excel文件
 */
public class POITest {

    /**
     * 通过POI创建Excel文件并写入文件内容
     *
     */
    public static void write() throws Exception{
        //在内存中创建一个Excel文件
        XSSFWorkbook excel = new XSSFWorkbook();
        //在Excel中创建一个Sheet页
        XSSFSheet sheet = excel.createSheet("info");
        //在Sheet页中创建行对象,rownum编号从0开始
        XSSFRow row = sheet.createRow(0);
        //创建单元格并写入文件内容
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("城市");


        //创建一个新行
        row = sheet.createRow(1);
        row.createCell(0).setCellValue("张三");
        row.createCell(1).setCellValue("北京");

        //创建一个新行
        row = sheet.createRow(2);
        row.createCell(0).setCellValue("李四");
        row.createCell(1).setCellValue("南京");

        //通过输出流将内存中的Excel文件写入到磁盘
        FileOutputStream out = new FileOutputStream(new File("D:\\zhuanye/info.xlsx"));
        excel.write(out);

        //关闭资源
        out.close();
        excel.close();

    }


    public static void main(String[] args) throws Exception{
        write();

    }
}

测试:

通过POI读取操作 

/**
 * 使用POI操作Excel文件
 */
public class POITest {

    
    /**
     * 通过POI读取Excel文件中的内容
     * @throws Exception
     */
    public static void read() throws Exception{
        FileInputStream in = new FileInputStream(new File("D:\\zhuanye/info.xlsx"));
        //读取磁盘上已经存在的excel文件
        XSSFWorkbook excel = new XSSFWorkbook(in);
        //读取Excel文件中的第一个sheet页

        XSSFSheet sheet = excel.getSheetAt(0);

        //获取sheet页中最后一行的行号
        int lastRowNum = sheet.getLastRowNum();

        for (int i = 0; i <= lastRowNum; i++) {
            //获得某一行
            XSSFRow row = sheet.getRow(i);

            //获得单元格对象
            String cellValue1 = row.getCell(0).getStringCellValue();
            String cellValue2 = row.getCell(1).getStringCellValue();
            System.out.println(cellValue1+" "+cellValue2);


        }

        //关闭资源
        excel.close();
        in.close();


    }


    public static void main(String[] args) throws Exception{

        read();
    }
}

测试:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值