在一個單元格內(nèi)實現(xiàn)文字換行,在文字后面加\r或\n無法做到。只能調(diào)用操作word相關addBreak方法達到想要的效果。
下面一張表格內(nèi)容,\n作為一個標志插入到文字內(nèi)容中,然后取到單元格文字內(nèi)容,查找\n標志,調(diào)用addBreak方法換行。


源碼:
private static void addBreakInCell(XWPFTableCell cell, String breakFlag) {
if (cell.getText() !=null && cell.getText().contains(breakFlag)) {
for (XWPFParagraph paragraph : cell.getParagraphs()) {
paragraph.setAlignment(ParagraphAlignment.LEFT);
for (XWPFRun run : paragraph.getRuns()) {
if (run.getText(0) !=null && run.getText(0).contains(breakFlag)) {
String runText = run.getText(0);
int preIndex =0;
int index = runText.indexOf(breakFlag);
// first row
? ? ? ? ? ? ? ? ? ? if (index >=0) {
run.setText("",0);
if (index ==0) {
run.addBreak();
run.setText(runText.replace(breakFlag,""));
index = runText.indexOf(breakFlag, index +1);
}
}
while (index >=0) {
String sub = runText.substring(preIndex, index);
sub = sub.replace(breakFlag,"");
if (sub.length() >0) {
run.setText(sub);
}
run.addBreak();
preIndex = index;
index = runText.indexOf(breakFlag, preIndex +1);
}
}
}
}
}
}
public static void addBreakToCell(String wordInPath, String wordOutPath) {
//獲取文檔doc
? ? XWPFDocument doc =null;
try {
doc =new XWPFDocument(new FileInputStream(wordInPath));
}catch (IOException e) {
e.printStackTrace();
}
Boolean exit =false;
//遍歷所有表格
? ? for(XWPFTable table : doc.getTables()) {
for(XWPFTableRow row : table.getRows()) {
List cells = row.getTableCells();
for(int i =0; i < cells.size(); i++) {
//單元格 : 直接cell.setText()只會把文字加在原有的后面,刪除不了文字
? ? ? ? ? ? ? ? XWPFTableCell cell = cells.get(i);
if (cell.getText().startsWith("描述情況")) {
if (i +1 < cells.size()) {
addBreakInCell(cells.get(i +1),"\\n");
exit =true;
break;
}
}
}
if (exit) {
break;
}
}
if (exit) {
break;
}
}
try {
doc.write(new FileOutputStream(wordOutPath));
}catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception {
? ? ? ? addBreakToCell("d:/test.docx","d:/result.docx");
}