POI-判断word文档(docx)中段落是否为标题段落
判断段落是否为标题需要获取段落的样式,样式可能基于某个样式,所以需要进行深度遍历,对深度遍历到的每个样式进行进行下面的判断逻辑。判断是否为标题,若是则停止遍历即可
一:判断是否有outlineLvl属性若有则为标题
二:判断样式名称是否是“heading 1”、“heading 2”、“heading 3”、“heading 4”、“heading 5”、“heading 6”、“heading 7”、“heading 8”、“heading 9”,若是则为标题
/** * 判断段落是否为标题段落 * @param paragraph 段落 * @param styles 文档中定义的样式 * @return */ public static boolean isTitle(XWPFParagraph paragraph, XWPFStyles styles) { String styleId = paragraph.getStyleID(); while(styleId != null) { final XWPFStyle style = styles.getStyle(styleId); if(style == null){ break; } boolean isTitle = XwpfStyleUtils.isTitleStyle(style); if(isTitle){ return true; } styleId = style.getBasisStyleID(); } return false; }
/** * @author joy * @date 2022/1/14 11:08 * docx样式 工具类 */ public class XwpfStyleUtils { /** * 获取大纲级别 * @param xwpfStyle 样式 * @return */ public static BigInteger getOutlineLvl(XWPFStyle xwpfStyle) { final CTStyle ctStyle = xwpfStyle.getCTStyle(); if(ctStyle != null) { final CTPPr pPr = ctStyle.getPPr(); if (pPr != null) { final CTDecimalNumber outlineLvl = pPr.getOutlineLvl(); if (outlineLvl != null) { return outlineLvl.getVal(); } } } return null; } /** * 判断是否是标题样式 * @param xwpfStyle 样式 * @return */ public static boolean isTitleStyle(XWPFStyle xwpfStyle){ final BigInteger outlineLvl = getOutlineLvl(xwpfStyle); if(outlineLvl != null && BigInteger.ZERO.compareTo(outlineLvl) <= 0){ return true; } return Arrays.stream(WordDocTitleEnum.values()).anyMatch(item -> item.getName().equals(xwpfStyle.getName())); } }
其中枚举类定义:
/** * @author joy * @date 2022/1/13 16:41 * WORD文档标题类型 */ public enum WordDocTitleEnum { ONE_LEVEL_TITLE("heading 1", "一级标题"), TWO_LEVEL_TITLE("heading 2", "二级标题"), THREE_LEVEL_TITLE("heading 3", "三级标题"), FOUR_LEVEL_TITLE("heading 4", "四级标题"), FIVE_LEVEL_TITLE("heading 5", "五级标题"), SIX_LEVEL_TITLE("heading 6", "六级标题"), SEVEN_LEVEL_TITLE("heading 7", "七级标题"), EIGHT_LEVEL_TITLE("heading 8", "八级标题"), NINE_LEVEL_TITLE("heading 9", "九级标题"); private final String name; private final String desc; WordDocTitleEnum(String name, String desc) { this.name = name; this.desc = desc; } public String getName() { return name; } public String getDesc() { return desc; } }