ooxml-schemas,IntelliJ IDEA和NullPointerException

时间:2019-02-21 00:04:27

标签: java apache intellij-idea apache-poi openxml

我试图使用某些需要ooxml-schemas jar的函数,即使在通过Maven导入poi-ooxml库和ooxml-schemas库之后,我仍然在第13行得到了NullPointerException。我正在使用IntelliJ IDEA 2017。

import java.io.*;
import java.math.BigInteger;
import org.apache.poi.util.Units;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

public class ASM {
    public static void main(String[] args) throws Exception {
        XWPFDocument document = new XWPFDocument();
        FileOutputStream out = new FileOutputStream(new File("AASM.docx"));
        CTSectPr sectPr = document.getDocument().getBody().getSectPr();
        CTPageSz pageSz = sectPr.getPgSz();
        double pageWidth = pageSz.getW().doubleValue();
        CTPageMar pageMar = sectPr.getPgMar();
        double pageMarginLeft = pageMar.getLeft().doubleValue();
        double pageMarginRight = pageMar.getRight().doubleValue();
        double effectivePageWidth = pageWidth - pageMarginLeft - pageMarginRight;
        //Header
        XWPFHeader header = document.createHeader(HeaderFooterType.DEFAULT);
        XWPFTable headerTable = header.createTable(1, 3);
        CTTblWidth width = headerTable.getCTTbl().addNewTblPr().addNewTblW();
        width.setType(STTblWidth.DXA);
        width.setW(new BigInteger(effectivePageWidth + ""));
        XWPFTableRow headerTableRowOne = headerTable.getRow(0);
        //Cell 0
        XWPFTableCell companyCell = headerTableRowOne.getCell(0);
        XWPFParagraph companyParagraph = companyCell.addParagraph();
        XWPFRun companyRun = companyParagraph.createRun();
        InputStream companyImageInputStream = new BufferedInputStream(new FileInputStream("20opy.png"));
        companyRun.addPicture(companyImageInputStream, Document.PICTURE_TYPE_PNG, "20opy.png", Units.toEMU(125), Units.toEMU(19));
        //Main Document
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("Hello world");
        run.addPicture(companyImageInputStream, Document.PICTURE_TYPE_PNG, "20opy.png", Units.toEMU(125), Units.toEMU(19));
        document.write(out);
        out.close();
        System.out.println("Finished");
    }
}

1 个答案:

答案 0 :(得分:2)

NullPointerException不能由缺少库引起。如果某个对象指向NPE,但代码尝试以某种方式尝试使用该对象,则会发生NULL

在您的情况下,如果sectPr.getPgSz()抛出NPE,则sectPrnull,因此null.getPgSz()抛出NPE

为什么sectPrnull?这是因为document.getDocument().getBody().getSectPr()返回了null。这是可以预期的,因为使用XWPFDocument新建的XWPFDocument document = new XWPFDocument();没有设置任何节属性。在部分和/或页面设置方面,它依赖于文字处理应用程序的默认设置。

清楚的是,您始终需要检查文档中是否已经有CTSectPr。而且,只有它们已经存在时,您才可以使用它们。否则,需要使用addNewSectPr创建它们。

您要获取页面设置的意图似乎是将表格的宽度设置为effectivePageWidth。但是由于新创建的XWPFDocument没有设置任何节属性,因此您需要首先进行设置,而不是尝试获取不存在的节属性。

在我使用过CTSectPr的代码示例中:https://stackoverflow.com/search?q=user%3A3915431+CTSectPr+