How to create a bulleted list in Apache POI XWPF Document?

后端 未结 5 515
鱼传尺愫
鱼传尺愫 2021-01-14 09:15

I want to create a bulleted/numbered list in a docx word document with Java. I am using the Apache POI 3.10 library. If I understand correctly, the steps would be like this:

5条回答
  •  忘掉有多难
    2021-01-14 09:35

    I found the easiest way was to extract numbering.xml from a Word document that has the style you want, and then manually recreate the important tags from the XML tree using Java. It sounds a bit painful, but it's much more precise than trying to parse something the MS Word has created. And the CT functions are named after the XML nodes that they affect, so it's fairly intuitive once you get the idea.

    For example in my case (this will return the correct CTAbstractNum for either a bulleted or numbered single-level list):

    private static CTAbstractNum getAbstractNumber(STNumberFormat.Enum numFmt) {
    
        CTAbstractNum ctAbsNum = CTAbstractNum.Factory.newInstance();
    
        CTLvl lvl = ctAbsNum.addNewLvl(); //Add a level
    
        CTDecimalNumber start = lvl.addNewStart(); //Set the starting number
        start.setVal(BigInteger.ONE);
    
        CTNumFmt fmt = lvl.addNewNumFmt(); //Set the number format
        fmt.setVal(numFmt);
    
        //Add the text that's used for the bullet point 
        CTLevelText lt = lvl.addNewLvlText(); 
        if (numFmt == STNumberFormat.BULLET) {
            lt.setVal("");     
            lvl.addNewRPr(); //Set the Symbol font
            CTFonts f = lvl.getRPr().addNewRFonts();
            f.setAscii("Symbol");
            f.setHAnsi("Symbol");
        }
        else { //Decimal
            lt.setVal("%1.");
        }
    
        lvl.addNewPPr(); 
        CTInd ind = lvl.getPPr().addNewInd(); //Set the indent
        ind.setHanging(BigInteger.valueOf(360));
        ind.setLeft(BigInteger.valueOf(720));           
    
        System.out.println(ctAbsNum);
    
        return ctAbsNum;
    }
    

提交回复
热议问题