Rok
Rok

Reputation: 55

Apache POI - multiple columns in a Word (docx) document

I'm trying to create a word document with multiple columns. The reason for doing this (rather than using tables) is that the data will span multiple pages and only with columns I can fill the whole page before adding to a new one.

Can it be done with Apache POI ? Thanks!

Upvotes: 4

Views: 2968

Answers (2)

flobbe9
flobbe9

Reputation: 34

Here's the solution using poi:

    XWPFDocument document = new XWPFDocument();
    CTBody ctBody = document.getDocument().getBody();
    CTSectPr ctSectPr = ctBody.getSectPr() == null ? ctBody.addNewSectPr() : ctBody.getSectPr();

    // add first column
    CTColumns column1 = ctSectPr.addNewCols();
    column1.setNum(BigInteger.valueOf(1));

    // add second column
    CTColumns column2 = ctSectPr.addNewCols();
    column2.setNum(BigInteger.valueOf(2));

To add text in both columns:

    XWPFParagraph paragraph = document.createParagraph();
    XWPFRun run = paragraph.createRun();

    // first line of column 1
    run.setText("col1");
    run.addBreak(BreakType.COLUMN);

    // first line of column 2
    run.setText("col2");

Upvotes: 0

Ivan Sopov
Ivan Sopov

Reputation: 2370

How about using previously created empty document with multiple columns? Like this:

    XWPFDocument document = new XWPFDocument(PoiTest.class.getResourceAsStream("twocolumn.docx"));
    XWPFParagraph tmpParagraph = document.getParagraphs().get(0);

    for (int i = 0; i < 100; i++) {
        XWPFRun tmpRun = tmpParagraph.createRun();
        tmpRun.setText("LALALALAALALAAAA");
        tmpRun.setFontSize(18);
    }
    document.write(new FileOutputStream(new File("C:\\temp\\poi.docx")));

Upvotes: 3

Related Questions