lucifer
lucifer

Reputation: 2327

How to do new line in doc using apache POI

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");

Upvotes: 5

Views: 24646

Answers (6)

hardik shah
hardik shah

Reputation: 3

Please check by increasing row height.

Upvotes: 0

Nils
Nils

Reputation: 119

Probably this is a bit late. I have a method where I create the headings of the table (row =0) and each heading has the heading number and then I add another paragraph with parameter text

public  static final String[] headings= {"Title", "Name", "Surname", "Address", "DOB","Notes"};

 '''
XWPFTableRow row = table.getRow(0);

for (int pos=0; pos < COLUMN_NUMBER; pos++) {
    addCellHeading(row, pos, headings[pos]);
}

...

private void addCellHeading(XWPFTableRow row, Integer pos, String text){

    XWPFTableCell cell = row.getCell(pos);
    XWPFParagraph headingNo = cell.addParagraph();
    headingNo.setAlignment(ParagraphAlignment.CENTER);
    XWPFRun run = headingNo.createRun();
    run.setBold(true);
    run.setText(String.valueOf(pos+1) + ". ");

    XWPFParagraph heading = cell.addParagraph();
    heading.setAlignment(ParagraphAlignment.CENTER);
    run = heading.createRun();
    run.setBold(true);
    run.setText(text);
}

Upvotes: 0

Denilson
Denilson

Reputation: 104

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();

Upvotes: 4

Abhishek Jaiswal
Abhishek Jaiswal

Reputation: 261

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);

Upvotes: 6

PCGerar
PCGerar

Reputation: 51

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++;
                }

Upvotes: 5

Dan Torrey
Dan Torrey

Reputation: 1469

Traditional carriage returns and line breaks are not recognized in Apache POI/OpenXML formats. Instead, the XWPFRun.addCarriageReturn() method needs to be called to create a new line.

You are going to need to loop through cell paragraphs and runs, then split the text you want to appear on new lines into new runs, then add a carriage return on all previous runs.

Here's some code to get you started. I did not test this, but I should get you going.

// Loop through paragraphs in cell.
for ( XWPFParagraph xwpfParagraph : cell.getParagraphs() ) {

    // Loop through runs in paragraph.
    for ( XWPFRun xwpfRun : xwpfParagraph.getRuns() ) {

        // 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 {
                    xwpfParagraph.insertNewRun( i );
                    XWPFRun newRun = paragraph.getRuns().get( i );
                    CTRPr rPr = newRun.getCTR().isSetRPr() ? newRun.getCTR().getRPr() : newRun.getCTR().addNewRPr();
                    rPr.set( xwpfRun.getCTR().getRPr() );
                    newRun.setText( textForLine );
                }
            }
        }
    }
}

Upvotes: 0

Related Questions