java word 單元格內(nèi)容換行

在一個單元格內(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");

}

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容