转换过程出现这个异常
Caused by: java.lang.NullPointerException
at org.apache.poi.xwpf.converter.core.styles.run.RunUnderlineValueProvider.getValue(RunUnderlineValueProvider.java:40)
查看源码得知是代码写的不严谨
return (rPr != null && rPr.isSetU()) ? UnderlinePatterns.valueOf(rPr.getU().getVal().intValue()) : null;
rPr.getU().getVal().intValue()这里容易出现空指针问题
解决办法:
- 在自己的项目中新建一个package名为org.apache.poi.xwpf.converter.core.styles.run
- 新建一个RunUnderlineValueProvider类,代码如下:
package org.apache.poi.xwpf.converter.core.styles.run;
import org.apache.poi.xwpf.converter.core.styles.XWPFStylesDocument;
import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTUnderline;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STUnderline.Enum;
/**
* 解决空指针异常,jar里面的写法不严谨
*/
public class RunUnderlineValueProvider extends AbstractRunValueProvider<UnderlinePatterns> {
public static final RunUnderlineValueProvider INSTANCE = new RunUnderlineValueProvider();
@Override
public UnderlinePatterns getValue(CTRPr rPr, XWPFStylesDocument stylesDocument) {
if(rPr == null) {
return null;
}
if(rPr.isSetU()) {
CTUnderline u = rPr.getU();
if(u != null) {
Enum val = u.getVal();
if(val != null) {
return UnderlinePatterns.valueOf(val.intValue());
}
}
}
return null;
// old code
// return (rPr != null && rPr.isSetU())
// ? UnderlinePatterns.valueOf(rPr.getU().getVal().intValue()) : null;
}
}
这样系统会优先调用.
本文介绍如何解决使用Apache POI进行Word文档转换时遇到的空指针异常问题。通过修改RunUnderlineValueProvider类,增强代码的健壮性。

3142

被折叠的 条评论
为什么被折叠?



