Independentsoft
- any library, any programming language
Home
Purchase
Support
Company
Contact
JWord
>
Tutorial
> Replace cell text
The example shows you how to find table cell and replace cell's text.
import java.util.List; import com.independentsoft.office.word.IBlockElement; import com.independentsoft.office.word.IParagraphContent; import com.independentsoft.office.word.IRunContent; import com.independentsoft.office.word.Paragraph; import com.independentsoft.office.word.Run; import com.independentsoft.office.word.Text; import com.independentsoft.office.word.WordDocument; import com.independentsoft.office.word.tables.Cell; import com.independentsoft.office.word.tables.Row; import com.independentsoft.office.word.tables.Table; public class Example { public static void main(String[] args) { try { WordDocument doc = new WordDocument("c:\\test\\input.docx"); List
tables = doc.getTables(); Table firstTable = tables.get(0); int rowCount = 0; int cellCount = 0; for (int i = 0; i < firstTable.getContent().size(); i++) { if (firstTable.getContent().get(i) instanceof Row) { Row row = (Row)firstTable.getContent().get(i); rowCount++; cellCount = 0; for (int j = 0; j < row.getContent().size(); j++) { if (row.getContent().get(j) instanceof Cell) { Cell cell = (Cell)row.getContent().get(j); cellCount++; if (rowCount == 3 && cellCount == 1) { String cellText = ""; Paragraph firstParagraph = null; Run firstRun = null; for (IBlockElement cellContent : cell.getContent()) { if (cellContent instanceof Paragraph) { Paragraph paragraph = (Paragraph)cellContent; if (firstParagraph == null) { firstParagraph = paragraph; } for (IParagraphContent paragraphContent : paragraph.getContent()) { if (paragraphContent instanceof Run) { Run run = (Run)paragraphContent; if (firstRun == null) { firstRun = run; } for (IRunContent runContent : run.getContent()) { if (runContent instanceof Text) { Text text = (Text)runContent; if (text.getValue() != null && text.getValue().length() > 0) { cellText += text.getValue(); } } } } } } } cellText = cellText.replace("oldText", "newText"); firstParagraph.getContent().clear(); firstRun.getContent().clear(); firstRun.add(new Text(cellText)); firstParagraph.add(firstRun); cell.getContent().clear(); cell.getContent().add(firstParagraph); } } } } } doc.save("c:\\test\\output.docx", true); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
Need help? Ask our developers:
Name*
Email*
Message*