我正在尝试使用某些需要 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");
}
}
最佳答案
NullPointerException
不能由缺少库引起。如果对象指向 NULL
但代码尝试以某种方式使用该对象,则会发生 NPE
。
在您的情况下,如果 sectPr.getPgSz()
抛出 NPE
,则 sectPr
为 null
,因此 null.getPgSz()
抛出 NPE
。
为什么sectPr
为null
?这是因为 document.getDocument().getBody().getSectPr()
返回了 null
。这是预期的,因为使用 XWPFDocument document = new XWPFDocument();
创建的新 XWPFDocument
没有设置任何节属性。当涉及到部分和/或页面设置时,它依赖于文字处理应用程序的默认设置。
很明显,您始终需要检查文档中是否已经存在 CTSectPr
。只有当它们已经存在时你才能使用它们。否则,需要使用 addNewSectPr
创建它们。
您获取页面设置的意图似乎是将表格的宽度设置为 effectivePageWidth
。但由于新创建的 XWPFDocument
没有设置任何节属性,因此您需要首先设置它们,而不是尝试获取不存在的内容。
查看我使用CTSectPr
的代码示例:https://stackoverflow.com/search?q=user%3A3915431+CTSectPr+
关于java - ooxml 架构、IntelliJ IDEA 和 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54797182/