在一个单元格内实现文字换行,在文字后面加\r或\n无法做到。只能调用操作word相关addBreak方法达到想要的效果。
下面一张表格内容,\n作为一个标志插入到文字内容中,然后取到单元格文字内容,查找\n标志,调用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");
}