poi解析word为html时空指针异常处理

我不是女神ヾ 2023-07-08 09:23 28阅读 0赞

poi操作word后,将生成的word解析为html时报空指针异常,于是跟踪代码发现三处poi的空指针异常处理不严谨的地方。

1.package org.apache.poi.xwpf.converter.core包下的XWPFDocumentVisitor类中的getXWPFNum方法

原代码:

  1. protected XWPFNum getXWPFNum(CTNumPr numPr) {
  2. CTDecimalNumber numID = numPr.getNumId();
  3. if (numID == null) {
  4. return null;
  5. } else {
  6. XWPFNum num = this.document.getNumbering().getNum(numID.getVal());
  7. return num;
  8. }
  9. }

修改后:

  1. protected XWPFNum getXWPFNum(CTNumPr numPr) {
  2. CTDecimalNumber numID = numPr.getNumId();
  3. if (Objects.isNull(numID)) {
  4. return null;
  5. }
  6. XWPFNumbering numbering = document.getNumbering();
  7. if (Objects.isNull(numbering)) {
  8. return null;
  9. }
  10. XWPFNum num = numbering.getNum(numID.getVal());
  11. return num;
  12. }

2.package org.apache.poi.xwpf.converter.core.styles.run包下的RunUnderlineValueProvider类中的getValue方法。

原代码:

  1. public UnderlinePatterns getValue(CTRPr rPr, XWPFStylesDocument stylesDocument) {
  2. return rPr != null && rPr.isSetU() ? UnderlinePatterns.valueOf(rPr.getU().getVal().intValue()) : null;
  3. }

修改后:

  1. @Override
  2. public UnderlinePatterns getValue(CTRPr rPr, XWPFStylesDocument stylesDocument) {
  3. if(rPr == null) {
  4. return null;
  5. }
  6. if(rPr.isSetU()) {
  7. CTUnderline u = rPr.getU();
  8. if(u != null) {
  9. Enum val = u.getVal();
  10. if(val != null) {
  11. return UnderlinePatterns.valueOf(val.intValue());
  12. }
  13. }
  14. }
  15. return null;

3.package org.apache.poi.xwpf.converter.core.styles.table.cell包下的TableCellWidthValueProvider类中的getTableWidth方法。

源代码:

  1. public TableWidth getTableWidth(CTTblWidth tblWidth) {
  2. if (tblWidth == null) {
  3. return null;
  4. } else {
  5. float width = XWPFTableUtil.getTblWidthW(tblWidth);
  6. boolean percentUnit = 2 == tblWidth.getType().intValue();
  7. if (percentUnit) {
  8. width /= 100.0F;
  9. } else {
  10. width = DxaUtil.dxa2points(width);
  11. }
  12. return new TableWidth(width, percentUnit);
  13. }
  14. }
  15. }

修改后:

  1. public TableWidth getTableWidth(CTTblWidth tblWidth) {
  2. if (tblWidth == null) {
  3. return null;
  4. } else {
  5. float width = XWPFTableUtil.getTblWidthW(tblWidth);
  6. boolean percentUnit = false;
  7. if(tblWidth.getType()!=null){
  8. percentUnit = 2 == tblWidth.getType().intValue();
  9. }
  10. if (percentUnit) {
  11. width /= 100.0F;
  12. } else {
  13. width = DxaUtil.dxa2points(width);
  14. }
  15. return new TableWidth(width, percentUnit);
  16. }
  17. }

4.修改源码并生效方法

在自己的工程下创建一个一模一样的包,然后创建一个一模一样的类,在新建的类中替换对应的方法。

发表评论

表情:
评论列表 (有 0 条评论,28人围观)

还没有评论,来说两句吧...

相关阅读