Apache POI 学习笔记

Apache POI 简介

它是用于操作 Microsoft 文档的 Java API。

XLS,DOC,PPT 格式的文档需要使用 HSSF, HWPDF,HSLF来处理。
XLSX, DOCX , PPTX 格式的文档需要使用 XSSF,XWPF,XSLF 来处理。

如果需要更多的学习资料,请访问官方网站:http://poi.apache.org/。

Apache POI 应用

一、添加依赖

<!-- Before Office 2007 -->
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>4.1.2</version>
</dependency>

<!-- After Office 2007 -->
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>4.1.2</version>
</dependency>

二、读写 Excel(xls, xlsx)

private static void creatExcel() {
    // 创建文档
    HSSFWorkbook wb = new HSSFWorkbook();

    // 如果不创建 Sheet 的话,则生成的文件在打开时会提示:
    // 发现 **.xls 中的部分内容有问题。是否让我们尽量尝试恢复?如果您信任此工作簿的源,请单击“是”。
    HSSFSheet sheet = wb.createSheet("Sheet");

    // 创建单元行
    HSSFRow row = sheet.createRow(0);

    // 创建单元格
    HSSFCell cellOne = row.createCell(0);
    cellOne.setCellValue("First Row And First Cell");

    HSSFCell cellTwo = row.createCell(1);
    cellTwo.setCellValue("First Row And Second Cell");

    // 设置单元格格式
    HSSFCellStyle style = wb.createCellStyle();
    // 设置单元格背景颜色 - 金黄色
    style.setFillForegroundColor(IndexedColors.GOLD.getIndex());
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    // 设置单元格背景颜色 - 粉红色
    HSSFCellStyle style2 = wb.createCellStyle();
    style2.setFillForegroundColor(IndexedColors.PINK.getIndex());
    style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    // 将单元格格式设置到具体的单元格
    cellOne.setCellStyle(style);
    cellTwo.setCellStyle(style2);

    // 设置第一列单元格的宽度为自适应。注意:这一行代码需要放在设置完内容之后,否则不起作用。
    sheet.autoSizeColumn(0);
    sheet.autoSizeColumn(1);

    try {
        OutputStream fileOut = new FileOutputStream(getHomeDirectory().concat("workbook.xls"));
        wb.write(fileOut);
    }catch (Exception ignored){}

    Workbook wb2 = new XSSFWorkbook();
    wb2.createSheet("Sheet");
    try {
        OutputStream fileOut = new FileOutputStream(getHomeDirectory().concat("workbook.xlsx"));
        wb2.write(fileOut);
    }catch (Exception ignored){}
}

private static void readAndWriteExcel() {
    try {
        InputStream inp = new FileInputStream(getHomeDirectory().concat("workbook.xls"));
        Workbook wb = WorkbookFactory.create(inp);
        Sheet sheet = wb.getSheetAt(0);
        Row row = sheet.getRow(0);

        Cell cellOne = row.getCell(0);
        // 防止单元格没有数据而产生 NPE
        if (cellOne == null){
            cellOne = row.createCell(0);
        }
        Cell cellTwo = row.getCell(1);
        if (cellTwo == null){
            cellTwo = row.createCell(1);
        }

        System.out.println(cellOne.getStringCellValue());
        System.out.println(cellTwo.getStringCellValue());

        cellTwo.setCellValue("First Row And Two Cell Modify");
        Cell cellThree = row.getCell(2);
        if (cellThree == null){
            cellThree = row.createCell(2);
        }
        sheet.autoSizeColumn(1);

        cellThree.setCellValue("First Row And Three Cell");
        sheet.autoSizeColumn(2);

        // Write the output to a file
        try  {
            OutputStream fileOut = new FileOutputStream(getHomeDirectory().concat("workbook.xls"));
            wb.write(fileOut);
        }catch (Exception ignored) {

        }
    }catch (Exception ignored){}
}

private static String getHomeDirectory(){
    // 获取系统桌面路径
    return FileSystemView.getFileSystemView().getHomeDirectory().toString().concat(File.separator);
}

官方说明:SXSSF 允许以内存优化的方式编写非常大的 Excel(XLSX)文件。
至于多大的文档属于非常大,我没有找到官方说明,也没有做测试,这里暂时不扩展。

二、读写 Word(docx)

private static void readAndWriteWord() throws Exception {
    InputStream inp = new FileInputStream(getHomeDirectory().concat("simple.docx"));
    XWPFDocument document = new XWPFDocument(inp);
    System.out.println(document.getParagraphs().get(0).getText());
}

private static void createWord() {
    // 1. 创建文档
    XWPFDocument docx = new XWPFDocument();
    // 2. 创建段落
    XWPFParagraph p1 = docx.createParagraph();
    // 3. 定义段落格式
    // a. 对齐方式
    p1.setAlignment(ParagraphAlignment.BOTH);
    // b. 段落间距。默认为1行。单位 磅
    p1.setSpacingBetween(30, LineSpacingRule.EXACT);
    // c. 首行缩进。数值的单位待调整。500大概为缩进2个字符。
    p1.setIndentationFirstLine(500);
    // 4. 定义文本区域
    XWPFRun r1 = p1.createRun();
    // a. 设置文本字体
    r1.setFontFamily("微软雅黑");
    // b. 设置文本内容
    r1.setText("一切有为法,如梦幻泡影。如露亦如电,应作如是观。凡所有相皆是虚妄,若见诸相非相,即见如来。若以色见我,以音声求我,是人行邪道,不能见如来。由爱故生忧,由爱故生怖。若离于爱者,无忧亦无怖。无上甚深微妙法,百千万劫难遭遇。我今见闻得受持,愿解如来真实义。");
    XWPFRun r2 = p1.createRun();
    // 加粗
    r2.setBold(true);
    r2.setText("如来者,无所从来,亦无所去,故名如来。");
    // 斜体
    r2.setItalic(false);
    // c. 添加超链接
    XWPFHyperlinkRun hyperlink = p1.createHyperlinkRun("http://poi.apache.org/");
    hyperlink.setUnderline(UnderlinePatterns.SINGLE);
    hyperlink.setColor("0000ff");
    hyperlink.setText("Apache POI");
    // 5. 设置第二个段落
    XWPFParagraph p2 = docx.createParagraph();
    // a. 此段落在新页上显示
    p2.setPageBreak(true);
    // b. 定义文本区域
    XWPFRun r21 = p2.createRun();
    r21.setFontFamily("微软雅黑");
    r21.setText("愿我来世,得菩提时,身如琉璃,内外明澈,净无瑕秽,光明广大。");
    // c. 创建表格
    XWPFTable table = docx.createTable(2, 2);
    // 设置第一个单元格的内容及格式
    XWPFParagraph cellOne = table.getRow(0).getCell(0).getParagraphs().get(0);
    XWPFRun r3 = cellOne.createRun();
    r3.setBold(true);
    r3.setFontFamily("微软雅黑");
    r3.setText("The quick brown fox");
    // 直接为指定单元格赋值
    table.getRow(0).getCell(1).setText("Row One Cell Two");
    table.getRow(1).getCell(0).setText("Row Two Cell One");
    table.getRow(1).getCell(1).setText("Row Two Cell Two");

    try {
        FileOutputStream out = new FileOutputStream(getHomeDirectory().concat("simple.docx"));
        docx.write(out);
    }catch (Exception ignore){}
}

private static String getHomeDirectory(){
    // 获取系统桌面路径
    return FileSystemView.getFileSystemView().getHomeDirectory().toString().concat(File.separator);
}

总结

上文是参考官方文档编写的应用代码。
更多的内容可阅读官方文档中的 API 说明 和 示例代码。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值