poi解析word为html时空指针异常处理
poi操作word后,将生成的word解析为html时报空指针异常,于是跟踪代码发现三处poi的空指针异常处理不严谨的地方。
1.package org.apache.poi.xwpf.converter.core包下的XWPFDocumentVisitor类中的getXWPFNum方法
原代码:
protected XWPFNum getXWPFNum(CTNumPr numPr) {
CTDecimalNumber numID = numPr.getNumId();
if (numID == null) {
return null;
} else {
XWPFNum num = this.document.getNumbering().getNum(numID.getVal());
return num;
}
}
修改后:
protected XWPFNum getXWPFNum(CTNumPr numPr) {
CTDecimalNumber numID = numPr.getNumId();
if (Objects.isNull(numID)) {
return null;
}
XWPFNumbering numbering = document.getNumbering();
if (Objects.isNull(numbering)) {
return null;
}
XWPFNum num = numbering.getNum(numID.getVal());
return num;
}
2.package org.apache.poi.xwpf.converter.core.styles.run包下的RunUnderlineValueProvider类中的getValue方法。
原代码:
public UnderlinePatterns getValue(CTRPr rPr, XWPFStylesDocument stylesDocument) {
return rPr != null && rPr.isSetU() ? UnderlinePatterns.valueOf(rPr.getU().getVal().intValue()) : null;
}
修改后:
@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;
3.package org.apache.poi.xwpf.converter.core.styles.table.cell包下的TableCellWidthValueProvider类中的getTableWidth方法。
源代码:
public TableWidth getTableWidth(CTTblWidth tblWidth) {
if (tblWidth == null) {
return null;
} else {
float width = XWPFTableUtil.getTblWidthW(tblWidth);
boolean percentUnit = 2 == tblWidth.getType().intValue();
if (percentUnit) {
width /= 100.0F;
} else {
width = DxaUtil.dxa2points(width);
}
return new TableWidth(width, percentUnit);
}
}
}
修改后:
public TableWidth getTableWidth(CTTblWidth tblWidth) {
if (tblWidth == null) {
return null;
} else {
float width = XWPFTableUtil.getTblWidthW(tblWidth);
boolean percentUnit = false;
if(tblWidth.getType()!=null){
percentUnit = 2 == tblWidth.getType().intValue();
}
if (percentUnit) {
width /= 100.0F;
} else {
width = DxaUtil.dxa2points(width);
}
return new TableWidth(width, percentUnit);
}
}
4.修改源码并生效方法
在自己的工程下创建一个一模一样的包,然后创建一个一模一样的类,在新建的类中替换对应的方法。
还没有评论,来说两句吧...