title: Write to word tablecell with Java, Apache POI?
body: <p>I have word document with a table. I want to insert text in those cells using Java and I have added Apache POI to my project.</p>
  
  <p>However, I have only succeeded to read from the document. My application gets all cells in the table. But I don't know how to insert new text in each cell? Any ideas?</p>
  
  <pre><code>  String SOURCE_FILE = "template.doc";
  
      DocumentProcessor instance = new DocumentProcessor();
      HWPFDocument doc = null;
      try {
          doc = instance.openDocument(SOURCE_FILE);
  
          Range range = doc.getRange();
          TableIterator itr = new TableIterator(range);
          while(itr.hasNext()) {
              Table table = itr.next();
              for (int rowIndex = 0; rowIndex &lt; table.numRows(); rowIndex++) {
                  TableRow row = table.getRow(rowIndex);
                  for (int colIndex = 0; colIndex &lt; row.numCells(); colIndex++) {
                      TableCell cell = row.getCell(colIndex);
                      cell.getParagraph(0).text().replace("", "Hello");
                      System.out.println(cell.getParagraph(0).text());
                  }
              }
          }
  
      } catch (Exception e) {
          e.printStackTrace();
      } finally {
          saveDocument(doc, SOURCE_FILE);
  
      }
  }
  
  
  private HWPFDocument openDocument(String file) throws Exception {
      URL res = getClass().getClassLoader().getResource(file);
      HWPFDocument document = null;
      if (res != null) {
          document = new HWPFDocument(new POIFSFileSystem(
                  new File(res.getPath())));
      }
      return document;
  }
  
  private static void saveDocument(HWPFDocument doc, String file) {
      try (FileOutputStream out = new FileOutputStream(file)) {
          doc.write(out);
          doc.close();
          System.out.println("File saved");
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
  </code></pre>