Apachepoi读写Excel实例

    /*
     * 通过poi创建Excel并写入内容
     * */
    public static void write() throws IOException {
        //在内存中创建excel
        XSSFWorkbook excel = new XSSFWorkbook();
        //在excel中创建sheet页,poi中默认sheet页不存在 需自己创建
        XSSFSheet sheet = excel.createSheet("infor");
        //在sheet页中创建行对象,rownum是从0开始 1是第二行
        XSSFRow row = sheet.createRow(1);
        //创建单元格写入文本内容
        row.createCell(1).setCellValue("姓名");
        //通过输出流将内存中的excel写到磁盘中
        FileOutputStream out = new FileOutputStream(new File("D:\\info.xlsx"));
        excel.write(out);
        //关闭资源
        out.close();
        excel.close();
    }
 /*
     * 通过poi读取excel文件
     * */
    public static void read() throws IOException {
        FileInputStream in = new FileInputStream(new File("D:\\info.xlsx"));
        //读取Excel文件封装进poi中
        XSSFWorkbook excel = new XSSFWorkbook(in);
        //读取sheet页
        XSSFSheet sheet = excel.getSheetAt(0);
        //获取sheet页中有文字的最后一行行号
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            //获取每一行对象
            XSSFRow row = sheet.getRow(i);
            String cellValue = row.getCell(1).getStringCellValue();
            System.out.println(cellValue);
        }
        in.close();
        excel.close();
    }

 当我们使用poi创建Excel时,有些Excel创建太过繁琐,因此我们会使用Windows自己创建一个Excel模板,再使用poi读取模板,写入数据

posted @ 2024-02-06 20:44  天启A  阅读(16)  评论(0)    收藏  举报