How to replace .docx table values using Apache POI

Here is an example on using Apache POI to read data from tables inside a .docx file and then write some data in it, the source also deletes the original file and replaces it for the corrected one. important thing about this code is that once you have downloaded the POI, the libs that you will get will not be enough to make it work!

You will need to download the ooxml-schemas-1.1.jar file and add it to your classpath, you can find it right here.

package br.com.vrsbrazil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class ReadWriteFile {

 /**
  * @param args
  * @throws IOException
  */

 public static void main(String[] args) throws IOException {

  final String[] folders = new String[]{"/SourceFolder"};
  final String newValue = "Test value\nFor new cell";

  for(String pastaPath:folders){

   final File folder = new File(pastaPath);

   for(File file:folder.listFiles()){

    if(file.getName().endsWith(".docx")) replaceTableValues(file,newValue);

   }

  }

 }

 public static void replaceTableValues(final File source,final String newValue) throws IOException {

  final File target = new File(source.getAbsolutePath()+".tmp");

  final XWPFDocument document = new XWPFDocument(new FileInputStream(source));

  for(int index=0;index<document.getTables().size();index++){

   final XWPFTable table = document.getTables().get(index);

   final XWPFTableCell cell = table.getRow(0).getCell(0);

   System.out.println("Current cell value: " + cell.getText());

   table.removeRow(0);

   final XWPFTableRow row = table.createRow();

   final XWPFTableCell novaCelula = row.createCell();

   final String[] linhas = newValue.split("\n");

   for(String s:linhas){

    final XWPFParagraph paragrafo =  novaCelula.addParagraph();

    paragrafo.createRun().setText(s);

   }

  }

  document.write(new FileOutputStream(target));

  final String newtargetPath = source.getAbsolutePath();

  source.delete();

  target.renameTo(new File(newtargetPath));

 }

}

Thank you for reading!

Advertisements

7 thoughts on “How to replace .docx table values using Apache POI”

  1. Hello,
    Im new at java. Im trying to make a app that can edit a docx template. the texts to be replace are inside a table.

    i came across this page and seem this is what im looking for. but it seems like im having difficulty making it work.

    im trying to run this in ecclipse.
    this is the 1st time i see a for loop that contains 4 entries. its getting red underlines. in line 46

    when i run the code. i get an error message on line 30. nullpointer exception. i already tried to place a docx file in there.

    1. about the line 46, i was able to run it. i read in some forum that &It is also <
      it ran..
      but not sure if behaving properly.

      1. Hi Edison,

        What was the outcome for you? This code only replaces the first row of the first line of a table, maybe you need to customize it…. you can see that at line 50.
        Let me know your thoughts!

      2. During the 1st run. the code is creating a new cell at the very last lower left and placing the new values in it.
        Then I did some modifications like you said in line 50. its working much better.

        Now I’m checking why is it not replacing the pre-existing data inside the cell… it just appends(add ups).

        Just like to say,
        Thank you very much for this code. I really found it very helpful 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s