使用Apache poi操作Excel

来源:互联网 发布:网络怎么开发客户 编辑:程序博客网 时间:2024/05/23 10:31

背景

昨天老妈让帮忙写个小程序解决个她工作里有关Excel数据的问题,其实感觉Excel玩的溜的选手也可以直接用Excel搞定,可惜在下才疏学浅,所以只能上咱笨重的java啦T_T。


Lets do it !

言归正传,既然选择用java解决这个问题,那么首先要搞定如何读写Excel文件,在这里我们选择Apache提供的poi来帮我们搞定这个问题。

首先,我们先在项目中添加poi相应的jar包

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

之后,先来一段读取Excel数据的代码

private void readData() throws Exception {        // poi读取excel        //创建要读入的文件的输入流        InputStream inp = new FileInputStream("data.xlsx");        //根据上述创建的输入流 创建工作簿对象        Workbook wb = WorkbookFactory.create(inp);        //得到第一页 sheet        //页Sheet是从0开始索引的        Sheet sheet = wb.getSheetAt(0);        //利用foreach循环 遍历sheet中的所有行        for (Row row : sheet) {                for (Cell cell : row) {                        System.out.print(cell.toString() + " ");                    }                }                System.out.println();            }        }        //关闭输入流        inp.close();    }

最后,将数保存到一个Excel的代码

private void saveData() throws Exception {        //创建excel工作簿        Workbook wb = new HSSFWorkbook();        //创建第一个sheet(页),命名为 foo        Sheet sheet = wb.createSheet("foo");        //Row 行        //Cell 方格        // Row 和 Cell 都是从0开始计数的        // 创建一行,在页sheet上        Row row0 = sheet.createRow(0);        row0.createCell(0).setCellValue("姓名");        row0.createCell(1).setCellValue("爱好");        Row row1 = sheet.createRow(1);        row1.createCell(0).setCellValue("Javie");        row1.createCell(1).setCellValue("Dota2");        //创建一个文件         FileOutputStream fileOut = new FileOutputStream("result.xls");        // 把上面创建的工作簿输出到文件中        wb.write(fileOut);        //关闭输出流        fileOut.close();    }

有了poi的帮助,剩下的就是对提取到的数据做相应的逻辑处理然后输出保存啦,EZ哼哼

0 0