Page 1 of 1

how to replace word with table in word07

PostPosted: Thu Jun 30, 2011 7:33 pm
by tosswang
i want to replace a word with a table in word07, the table i have created,but i don't know how to replace a word, please help me

Re: how to replace word with table in word07

PostPosted: Thu Jun 30, 2011 9:04 pm
by tinne
You cannot replace a word with a table, but any paragraph-like structure. If you read the wml schema, you will find a group called EG_ContentBlockContent, which may contain p and tbl elements. Thus, the proper way to do it is to identify your word, find the enclosing org.docx4j.wml.P, and replace it in its parents list with a org.docx4j.wml.Tbl of your choice.

Re: how to replace word with table in word07

PostPosted: Fri Jul 01, 2011 12:02 am
by tosswang
tinne wrote:You cannot replace a word with a table, but any paragraph-like structure. If you read the wml schema, you will find a group called EG_ContentBlockContent, which may contain p and tbl elements. Thus, the proper way to do it is to identify your word, find the enclosing org.docx4j.wml.P, and replace it in its parents list with a org.docx4j.wml.Tbl of your choice.


thanks tinne,i am new to docx4j, can you give me a more detailed example?

Re: how to replace word with table in word07

PostPosted: Fri Jul 01, 2011 9:18 am
by tinne
I am not quite sure how to help. There are examples in the forum archives about table construction and convenience methods about doing so, and other examples about searching a document e.g. via xpath expressions.

This, however, will not stop you from the need of basic skills in JAXB and the ISO 29500 standard xml grammars.

Please, give it a try and in case of more concrete problems, come back and ask.

java.util.ConcurrentModificationException

PostPosted: Tue Jul 05, 2011 8:44 pm
by tosswang
i want to replace a text with atable ,below is my code snippet :
Code: Select all
public class OpenMainDocumentAndTraverse extends AbstractSample
{
   
   /**
    * @param args
    */
   public static void main(String[] args) throws Exception
   {
      
      try
      {
         getInputFilePath(args);
      }
      catch (IllegalArgumentException e)
      {
         inputfilepath = System.getProperty("user.dir")
               + "/sample-docs/sample-docx.xml";
      }
      
      WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
            .load(new java.io.File(inputfilepath));
      final MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
      
      org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart
            .getJaxbElement();
      Body body = wmlDocumentEl.getBody();
                  
      new TraversalUtil(body,

      new Callback()
      {
         
         String indent = "";
         
         org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
         
         org.docx4j.wml.R tmpR = factory.createR();
                        
         public List<Object> apply(Object o)
         {
            
            String text = "";
            
            if (o instanceof org.docx4j.wml.Text)
            {
               org.docx4j.wml.Text t = (org.docx4j.wml.Text) o;                              
                              
               if (text.equals("[Name]"))
               {                                 
                  t.setValue("");
                  Tbl table =TblFactory.createTable(3, 4, 500);      //create a table
                            documentPart .addObejct(table );
               }
            }
            
            if (o instanceof org.docx4j.wml.R)
            {
               tmpR = (org.docx4j.wml.R) o;
            }
            
            return null;
         }
         
         public boolean shouldTraverse(Object o)
         {
            return true;
         }
         
         public void walkJAXBElements(Object parent)
         {
            
            indent += "    ";            
            List children = getChildren(parent);
            if (children != null)
            {               
               for (Object o : children)
               {
                           
                  o = XmlUtils.unwrap(o);
                  
                  this.apply(o);
                  
                  if (this.shouldTraverse(o))
                  {
                     walkJAXBElements(o);
                  }
                  
               }
               
            }
            
            indent = indent.substring(0, indent.length() - 4);
         }
         
         public List<Object> getChildren(Object o)
         {
            return TraversalUtil.getChildrenImpl(o);
         }
         
      }

      );
      
      wordMLPackage.save(new File("c:\\workspace\\test_out.docx"));
      
   }
   
}

below is Tbl snippet
Code: Select all
public static Tbl createTable(int rows, int cols, int cellWidthTwips)
{
      
      org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
      
      Tbl tbl = factory.createTbl();
      
      // w:tblPr
      String strTblPr = "<w:tblPr " + Namespaces.W_NAMESPACE_DECLARATION
            + ">" + "<w:tblStyle w:val=\"TableGrid\"/>"
            + "<w:tblW w:w=\"0\" w:type=\"auto\"/>"
            + "<w:tblLook w:val=\"04A0\"/>" + "</w:tblPr>";
      TblPr tblPr = null;
      try
      {
         tblPr = (TblPr) XmlUtils.unmarshalString(strTblPr);
      }
      catch (JAXBException e)
      {
         // Shouldn't happen
         e.printStackTrace();
      }
      tbl.setTblPr(tblPr);
      
      // <w:tblGrid><w:gridCol w:w="4788"/>
      TblGrid tblGrid = factory.createTblGrid();
      tbl.setTblGrid(tblGrid);
      // Add required <w:gridCol w:w="4788"/>
      for (int i = 1; i <= cols; i++)
      {
         TblGridCol gridCol = factory.createTblGridCol();
         gridCol.setW(BigInteger.valueOf(cellWidthTwips));
         tblGrid.getGridCol().add(gridCol);
      }
   
      for (int j = 1; j <= rows; j++)
      {
         Tr tr = factory.createTr();
         tbl.getContent().add(tr);
         
         // The cells
         for (int i = 1; i <= cols; i++)
         {
            
            Tc tc = factory.createTc();
            tr.getContent().add(tc);
            
            TcPr tcPr = factory.createTcPr();
            
            CTVerticalJc vertical=factory.createCTVerticalJc();
            vertical.setVal(STVerticalJc.CENTER);
            tcPr.setVAlign(vertical);
            
            
            tc.setTcPr(tcPr);
            
            // <w:tcW w:w="4788" w:type="dxa"/>
            TblWidth cellWidth = factory.createTblWidth();
            tcPr.setTcW(cellWidth);
            cellWidth.setType("dxa");
            cellWidth.setW(BigInteger.valueOf(cellWidthTwips));
            
            // Cell content - an empty <w:p/>
            org.docx4j.wml.P p = factory.createP();
            
            org.docx4j.wml.PPr ppr=factory.createPPr();
            org.docx4j.wml.Jc jc=factory.createJc();
            jc.setVal(JcEnumeration.CENTER);
            ppr.setJc(jc);
            
            p.setPPr(ppr);
            
            org.docx4j.wml.Text t = factory.createText();
            t.setValue("hi");
            org.docx4j.wml.R run = factory.createR();
            run.getContent().add(t);
            p.getContent().add(run);
            
            tc.getContent().add(p);
         }
         
      }
      return tbl;
   }

the result of running is Exception in thread "main" java.util.ConcurrentModificationException,how can i avoid this issue and insert a table?

the attach is a example doc which is used in this program.

thanks in advance!

Re: how to replace word with table in word07

PostPosted: Wed Jul 06, 2011 3:48 pm
by tosswang
who can help me?

Re: how to replace word with table in word07

PostPosted: Wed Jul 06, 2011 11:52 pm
by jason
I can't see how your code snippet would even compile, given that it contains " documentPart .addObejct(table );"

You don't tell us which part of your code is causing the exception.

If you post a complete standalone class which compiles against docx4j 2.7.0 rc 2, someone may take a look at it for you.

You are more likely to get help if you take heed of Tinne's earlier advice that you can only insert a table as a sibling to paragraph. So either you replace the paragraph containing your text, or you split the paragraph into p1 + table + p2.

Also the cause of your exception is likely to be trying to modify the list you are currently traversing. So you should split this into 2 operations. First, traverse to find the spot you wish to insert your table, and store this. After traversal is complete, your second step is to do the actual insertion.

Re: how to replace word with table in word07

PostPosted: Thu Jul 07, 2011 9:42 pm
by tosswang
hi,jason:
below is my code,i resolve it,it can run, but i can't remove the word 'ssss',i only set it empty string ,can you help me?
Code: Select all
   package org;

import java.io.File;
import java.math.BigInteger;
import java.util.List;

import javax.xml.bind.JAXBException;

import org.docx4j.XmlUtils;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.openpackaging.parts.relationships.Namespaces;
import org.docx4j.wml.CTVerticalJc;
import org.docx4j.wml.JcEnumeration;
import org.docx4j.wml.STVerticalJc;
import org.docx4j.wml.Tbl;
import org.docx4j.wml.TblGrid;
import org.docx4j.wml.TblGridCol;
import org.docx4j.wml.TblPr;
import org.docx4j.wml.TblWidth;
import org.docx4j.wml.Tc;
import org.docx4j.wml.TcPr;
import org.docx4j.wml.Tr;

public class XPathQuery {

   public static Tbl createTable(int rows, int cols, int cellWidthTwips)
   {
      
      org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
      
      Tbl tbl = factory.createTbl();
   
      String strTblPr = "<w:tblPr " + Namespaces.W_NAMESPACE_DECLARATION
            + ">" + "<w:tblStyle w:val=\"TableGrid\"/>"
            +"<w:tblW w:w=\"0\" w:type=\"auto\"/>"+"<w:tblBorders>"
            +"<w:top w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"auto\" /> "
            +"<w:left w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"auto\" /> "
            +"<w:bottom w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"auto\" /> "
            +"<w:right w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"auto\" /> "
            +"<w:insideH w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"auto\" /> "
            +"<w:insideV w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"auto\" /> "
            +"</w:tblBorders>"
            + "<w:tblLook w:val=\"04A0\"/>" + "</w:tblPr>";
      TblPr tblPr = null;
      try
      {
         tblPr = (TblPr) XmlUtils.unmarshalString(strTblPr);
      }
      catch (JAXBException e)
      {         
         e.printStackTrace();
      }
      tbl.setTblPr(tblPr);
   
      TblGrid tblGrid = factory.createTblGrid();
      tbl.setTblGrid(tblGrid);
   
      for (int i = 1; i <= cols; i++)
      {
         TblGridCol gridCol = factory.createTblGridCol();
         gridCol.setW(BigInteger.valueOf(cellWidthTwips));
         tblGrid.getGridCol().add(gridCol);
      }
   
      for (int j = 1; j <= rows; j++)
      {
         Tr tr = factory.createTr();
         tbl.getContent().add(tr);
   
         for (int i = 1; i <= cols; i++)
         {
            
            Tc tc = factory.createTc();
            tr.getContent().add(tc);
            
            TcPr tcPr = factory.createTcPr();
            
            CTVerticalJc vertical=factory.createCTVerticalJc();
            vertical.setVal(STVerticalJc.CENTER);
            tcPr.setVAlign(vertical);
            
            
            tc.setTcPr(tcPr);
   
            TblWidth cellWidth = factory.createTblWidth();
            tcPr.setTcW(cellWidth);
            cellWidth.setType("dxa");
            cellWidth.setW(BigInteger.valueOf(cellWidthTwips));
            
            org.docx4j.wml.P p = factory.createP();
            
            org.docx4j.wml.PPr ppr=factory.createPPr();
            org.docx4j.wml.Jc jc=factory.createJc();
            jc.setVal(JcEnumeration.CENTER);
            ppr.setJc(jc);
            
            p.setPPr(ppr);
            
            org.docx4j.wml.Text t = factory.createText();
            t.setValue("hi");
            org.docx4j.wml.R run = factory.createR();
            run.getContent().add(t);
            p.getContent().add(run);            
            tc.getContent().add(p);
         }
         
      }
      return tbl;
   }
   
   public static void main(String[] args) throws Exception {

      String inputfilepath = "c:/workspace/Table.docx";
            
      WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));      
      MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
                  
      String xpath = "//w:p[w:r[w:t[contains(text(),'ssss')]]]";
      
      List<Object> list = documentPart.getJAXBNodesViaXPath(xpath, false);
      
      for (Object o : list) {
      
         Object o2 = XmlUtils.unwrap(o);
         
         if(o2 instanceof org.docx4j.wml.P)
         {
            org.docx4j.wml.P p=(org.docx4j.wml.P)o2;
            
            xpath = "//w:t[contains(text(),'ssss')]";            
            List<Object> list1 = documentPart.getJAXBNodesViaXPath(xpath, false);   
            
            for(Object o1:list1)
            {
               System.out.println(o1.getClass().getName() );
      
               Object o3 = XmlUtils.unwrap(o1);
               System.out.println(o3.getClass().getName() );
               if (o3 instanceof org.docx4j.wml.Text)/**(3)***/
               {
                  System.out.println("Hello");
                  org.docx4j.wml.Text r=(org.docx4j.wml.Text)o3;
                  if(r.getValue().equals("ssss"))
                  {
                     r.setValue("");
                  }
                  
               }
            }
            

            Tbl table = createTable(1, 1, 500);
            p.getContent().add(table);                        
         }
         
         if (o2 instanceof org.docx4j.wml.Text) {
            
            org.docx4j.wml.Text txt = (org.docx4j.wml.Text)o2;
            
            Object parent = txt.getParent();
      
         }         
         
      }
      
      wordMLPackage.save(new File( "c:/workspace/test-tb.docx"));
      
   }
      
}

   


the attach is a example doc which is used in this program.
thanks in advance!

Re: how to replace word with table in word07

PostPosted: Thu Jul 07, 2011 11:48 pm
by jason
What about something like:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting

      WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));      
      MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
                 
      String xpath = "//w:r[w:t[contains(text(),'ssss')]]";
     
      List<Object> list = documentPart.getJAXBNodesViaXPath(xpath, false);
     
      if (list.isEmpty()) {
          System.out.println("Couldn't find the run");
          return;
      }
     
      R r = (R)list.get(0);
      P parent = (P)r.getParent();
     
      int index = documentPart.getContent().indexOf(parent);
     
      // we could just remove the 'ssss' run
      // parent.getContent().remove(r);
      // but probably that's not what you want
      // since it will leave an empty p,
      // so let's remove the whole p
      documentPart.getContent().remove(parent);
     
      // Now add the table
      Tbl table = createTable(1, 1, 500);
     
      documentPart.getContent().add(index, table);
     
      System.out.println(XmlUtils.marshaltoString(documentPart.getJaxbElement(), true));
 
Parsed in 0.016 seconds, using GeSHi 1.0.8.4

Re: how to replace word with table in word07

PostPosted: Fri Jul 08, 2011 2:53 pm
by tosswang
thanks jason,the problem have resolved! :D