How to do new line in doc using apache POI

19,013

Solution 1

This code worked for me with some modifications (the loop has some errors finding the last run and forgets to insert the new line on the others paragraphs) (Edited: *and as dellasavia said: a "while" is better than a "for each" to avoid the exception).

                // Loop through runs in paragraph.
                int i_paragraph = 0;
                //for (XWPFRun xwpfRun : parrafo.getRuns()) { //EXCEPTION UPDATING RUNS IN THE PARAGRAPH
                while (i_paragraph < parrafo.getRuns().size()) { //BETTER THE WHILE
                    XWPFRun xwpfRun = parrafo.getRuns().get(i_paragraph);

                    // Split runs by new line character.
                    String textOfRun = xwpfRun.getText(0);
                    if (textOfRun.contains("\n")) {
                        String[] stringsOnNewLines = textOfRun.split("\n");

                        // For each additional line, create a new run. Add carriage return on previous.
                        for (int i = 0; i < stringsOnNewLines.length; i++) {

                            // For every run except last one, add a carriage return.
                            String textForLine = stringsOnNewLines[i];
                            if (i == stringsOnNewLines.length - 1) {
                                xwpfRun.setText(textForLine, 0);
                                xwpfRun.addCarriageReturn();
                            } else {
                                parrafo.insertNewRun(i);
                                XWPFRun newRun = parrafo.getRuns().get(i);
                                CTRPr rPr = newRun.getCTR().isSetRPr() ? newRun.getCTR().getRPr() : newRun.getCTR().addNewRPr();
                                rPr.set(xwpfRun.getCTR().getRPr());
                                newRun.setText(textForLine);
                                newRun.addCarriageReturn(); //ADD THE NEW LINE
                            }
                        }
                    }
                    i_paragraph++;
                }

Solution 2

To add formating to table cell, create a function which takes paragraph and string as argument. This function will create a run from the para, now you can add your formating to this run.

private static void tableText(List<XWPFParagraph> paragraph, String text) {
    XWPFRun run = paragraph.get(0).createRun();
    run.setFontSize(14);
    run.setFontFamily("Times New Roman");
    run.setText(text);
    run.addBreak();
    run.setText("Next line");
}

Now use this function to add text to table.

XWPFTableRow tableRow = table.createRow();
tableText(tableRow.getCell(0).getParagraphs(), " 6 ", true);

Solution 3

The POI website lists a technique that works for me.

https://poi.apache.org/spreadsheet/quick-guide.html#Using+newlines+in+cells

Using newlines in cells

Workbook wb = new XSSFWorkbook();   //or new HSSFWorkbook();
Sheet sheet = wb.createSheet();

Row row = sheet.createRow(2);
Cell cell = row.createCell(2);
cell.setCellValue("Use \n with word wrap on to create a new line");

//to enable newlines you need set a cell styles with wrap=true
CellStyle cs = wb.createCellStyle();
cs.setWrapText(true);
cell.setCellStyle(cs);

//increase row height to accomodate two lines of text
row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));

//adjust column width to fit the content
sheet.autoSizeColumn((short)2);

FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
wb.write(fileOut);
fileOut.close();
Share:
19,013

Related videos on Youtube

lucifer
Author by

lucifer

Updated on September 15, 2022

Comments

  • lucifer
    lucifer about 1 year

    I am creating a table using POI in word the table is created successfully but i want to do a new line between each text in a cell ,I am not able to do that,here is what i have done so far,

    XWPFTable candidateTrackerTable = document.createTable();
    XWPFTableRow canndidateTrackerTableRowOne =  candidateTrackerTable.getRow(0);
    canndidateTrackerTableRowOne.getCell(0).setText("Presented ");
    canndidateTrackerTableRowOne.addNewTableCell().setText("Interview ");
    canndidateTrackerTableRowOne.addNewTableCell().setText("Phone ");
    canndidateTrackerTableRowOne.addNewTableCell().setText("Final Interview ");
    canndidateTrackerTableRowOne.addNewTableCell().setText("Offer ");
    
    XWPFTableRow canndidateTrackerTableRowTwo = null;
    for(Map.Entry<Integer, ArrayList<String>> candidateName:aMap.entrySet()){
        canndidateTrackerTableRowTwo =  candidateTrackerTable.createRow();
        for(String s:candidateName.getValue()){
            //System.out.println("------>>"+s);
            canndidateTrackerTableRowTwo.getCell(0).setText(String.valueOf(s)+"\n");
        }
        for(Map.Entry<Integer, ArrayList<String>> candidatePhone:bMap.entrySet()){
            for(String s1:candidatePhone.getValue()){
                //System.out.println("------>>"+s1);
                canndidateTrackerTableRowTwo.getCell(1).setText(String.valueOf(s1));
            }
            for(Map.Entry<Integer, ArrayList<String>> candidateSkyped: cMap.entrySet())
                for(String s2:candidateSkyped.getValue())
                    canndidateTrackerTableRowTwo.getCell(2).setText(String.valueOf(s2));
            for(Map.Entry<Integer, ArrayList<String>> candidateOnsite : dMap.entrySet())
                for(String s3:candidateOnsite.getValue())
                    canndidateTrackerTableRowTwo.getCell(3).setText(String.valueOf(s3));
            for(Map.Entry<Integer, ArrayList<String>> candidateOffered : eMap.entrySet())
                for(String s4:candidateOffered.getValue())
                    canndidateTrackerTableRowTwo.getCell(4).setText(String.valueOf(s4));
        }
    }       
    

    i want to add new line between each canndidateTrackerTableRowTwo.getCell(0).setText(String.valueOf(s)+"\n");

  • deldev
    deldev over 8 years
    In xwpfParagraph.insertNewRun( i ); does not cause ConcurrentModificationException, once xwpfParagraph is being iterated?
  • Ermintar
    Ermintar over 2 years
    @dellasavia, yeah, it does.
  • shikida
    shikida almost 2 years
    adding breaks solved my problem. upvoted