问题描述
我试图使用某些需要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楼
NullPointerException
不能由缺少库引起。
如果对象指向NULL
但是代码尝试以某种方式使用该对象,则会发生NPE
。
在您的情况下,如果sectPr.getPgSz()
抛出NPE
,则sectPr
为null
,因此null.getPgSz()
抛出NPE
。
为什么sectPr
为null
?
这是因为document.getDocument().getBody().getSectPr()
返回了null
。
这是可以预期的,因为使用XWPFDocument document = new XWPFDocument();
创建了一个新的XWPFDocument
XWPFDocument document = new XWPFDocument();
没有设置任何节属性。
当涉及到部分和/或页面设置时,它依赖于文字处理应用程序的默认设置。
清楚的是,您始终需要检查文档中是否已经存在CTSectPr
。
而且,只有它们已经存在时,您才可以使用它们。
否则,需要使用addNewSectPr
创建addNewSectPr
。
您想要获取页面设置的目的似乎是将表的宽度设置为effectivePageWidth
。
但是由于新创建的XWPFDocument
没有设置任何节属性,因此您需要首先设置它们,而不是尝试获取不存在的属性。
请参阅我使用过CTSectPr
的代码示例: : CTSectPr
CTSectPr
CTSectPr