13

Hoping someone might have some experience with this. I'm using Apache POI 3.8b4 to output a table in Word 2007 format. When I do something similar to the following:

XWPFTableRow row = table.getRow(0);
String text = "A\nB\nC\nD";
row.getCell(i).setText(text);

all of my line breaks are ignored in the output in the table cell looks like

A B C D

Does anyone have any idea how to get it to properly display as

A
B
C
D

Edit: The solution was the following:

XWPFParagraph para = row.getCell(i).getParagraphs().get(0);
for(String text : myStrings){
    XWPFRun run = para.createRun();
    run.setText(text.trim());
    run.addBreak();
}
ratherOCD
  • 167
  • 1
  • 1
  • 7
  • Have you tried /r/n? Or System.properties("line.separator")? – John B Sep 19 '11 at 21:13
  • Unless I misunderstood this - you are adding cells in a row, so they will be in 4 adjacent cells. For what you are trying to do you need to create a new row for each character. – CoolBeans Sep 19 '11 at 21:18
  • If you do the same thing in Word, what XML does it generate for the cell? Does it just do literal newlines, or does it do something fancy like multiple paragraphs in the cell? – Gagravarr Sep 19 '11 at 21:19
  • Please clarify, are attempting to add 4 vertical cells to a table, or 4 lines of text to a single cell? – John B Sep 19 '11 at 21:28
  • @JohnB Yes I tried both of those. I am attempting to add 4 lines of text to a single cell. I suspect adding new paragraphs will work and will give that a shot. @Gagravarr Looking at the xml, it seems as though a soft return adds a new run with a `` element, wheras a crlf seems to add a new paragraph. – ratherOCD Sep 20 '11 at 12:21

5 Answers5

2

Try this way :

XWPFParagraph paragraph = document.createParagraph();
XWPFRun run=paragraph.createRun();
run.setText("A");
run.addBreak();
run.setText("B");
run.addBreak();
run.setText("C");
document.write(OutPutFilePath);
CinCout
  • 9,486
  • 12
  • 49
  • 67
Anoop Rana
  • 21
  • 4
1

Try this:

String text = ".. ... some text with line breaks... ...";
String[] textLines = text.split(System.lineSeparator());
for(String s : textLines) {
  run.setText(s);
  run.addBreak(BreakType.TEXT_WRAPPING);
}
FazoM
  • 4,777
  • 6
  • 43
  • 61
0

Try this way :

for(String text : myStrings){
XWPFParagraph para = row.getCell(i).getParagraphs().get(0);
XWPFRun run = para.createRun();
run.setText(text.trim());
run.addBreak();

}

0
XWPFRun run=paragraph.createRun();
run.setText("StringValue".trim());
run.addBreak();
document.write(OutPutFilePath);
0

Have you tried adding multiple Paragraphs?

Add Paragraph

John B
  • 32,493
  • 6
  • 77
  • 98
  • I actually wanted a soft break, so I needed to get the existing paragraph, add a run, and then add a break in the run, but this basically got me on the right path. – ratherOCD Sep 20 '11 at 13:16