简介

poi是apache的开源项目,它可以操作microsoft 文件,比如Excel (SS=HSSF+XSSF)、Word (HWPF+XWPF)、PowerPoint (HSLF+XSLF),括号里的是操作相应文件用到的类,我们这里主要介绍操作excel的HSSF和XSSF。

hssf和xssf

通过HSSF和XSSF操作excel,HSSF和XSSF提供了读取、写入、修改excel的方法。那么HSSF和XSSF有什么不同呢?

  • HSSF是纯java实现,来操作97-2007版本的excel,也就是xls格式的。
  • XSSF主要用来操作2007版及以后的excel,也就是xlsx。
  • poi 3.8-beta3版本推出了SXSSF ,SXSSF 是基于xsff做的,它占用的内存更低,尤其在读取大excel时更为明显。原理很简单,就是限制行数,当有新行载入时,最小索引的那行会被写入磁盘。而XSSF不会限制行数,所以会占用更多的内存。

导出

导出excel的原理很简单,就是创建workbook、然后创建sheet,然后创建行,行再创建单元格,设置值。

System.out.println("生成文件的所在目录:"+System.getProperty("user.dir"));

        Workbook wb = new HSSFWorkbook();
        // Workbook wb = new XSSFWorkbook();
        CreationHelper createHelper = wb.getCreationHelper();
        Sheet sheet = wb.createSheet("new sheet");

        // Create a row and put some cells in it. Rows are 0 based.
        Row row = sheet.createRow((short) 0);
        // Create a cell and put a value in it.
        Cell cell = row.createCell(0);
        cell.setCellValue(1);

        // Or do it on one line.
        row.createCell(1).setCellValue(1.2);
        row.createCell(2).setCellValue(
                createHelper.createRichTextString("This is a string"));
        row.createCell(3).setCellValue(true);

        // Write the output to a file
        FileOutputStream fileOut;
        try {
            fileOut = new FileOutputStream("workbook.xls");
            wb.write(fileOut);
            fileOut.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

更多的样例,可以参考poi官方文档,只要理解了原理,这些都是熟练活。

参考

POI-HSSF and POI-XSSF - Java API To Access Microsoft Excel Format Files