我正在尝试从 java 应用程序创建一个 word 文档,并使用 Apache POI 稳定版本 3.7 来实现相同的目的。当我尝试更改段落的字体时,即使字体系列存在,我也会遇到空指针异常。事实上,如果我用任何字体系列调用该函数,它都会给出 npe。代码如下:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
/**
*
* @author william
*/
public class CreateDocumentFromScratch
{
public static void main(String[] args)
{
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraphOne = document.createParagraph();
XWPFRun paragraphOneRunOne = paragraphOne.createRun();
paragraphOneRunOne.setFontFamily("Arial");
paragraphOneRunOne.setText("Hello");
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream("c:/will/First.docx");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
document.write(outStream);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这里是异常(exception):
run:
Exception in thread "main" java.lang.NullPointerException
at org.apache.poi.xwpf.usermodel.XWPFRun.setFontFamily(XWPFRun.java:413)
at pdftest.CreateDocumentFromScratch.main(CreateDocumentFromScratch.java:30)
知道我做错了什么吗?另外,Apache POI 创建格式化 Word 文档的可靠性如何?
最佳答案
这是 3.7 中的一个错误:
http://apache-poi.1045710.n5.nabble.com/NPE-setting-font-family-for-a-XWPFRun-td5050524.html
但是可以在 3.8 中使用(目前处于测试版):
https://issues.apache.org/bugzilla/show_bug.cgi?id=52288
关于java - Apache POI SetFontFamily,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9225307/