Domanda

I have found tutorials on how to make a simple table in generating a docx file using docx4j. and have seen a sample on how to merge cells vertically. It worked. but i have tried the same using horizontal merge. but nothing happend. How do I use the HMerge? I have found that the values of this class can be "restart" or "continue". what can those values do? here's a sample code.

Tbl tblGI = factory.createTbl();
Tr trGI = factory.createTr();

Tc tcGI1 = factory.createTc();
TcPr tcpr = new TcPr();
HMerge hmerge = new HMerge();
hmerge.setVal("restart");
tcpr.setHMerge(hmerge);
tcGI1.setTcPr(tcpr);
tcGI1.getContent().add(wordMLPackage.getMainDocumentPart().createParagraphOfText("sample merged cell"));
trGI.getContent().add(tcGI1);

Tr trGI2 = factory.createTr();
Tc tcGI21 = factory.createTc();
tcGI21.getContent().add(wordMLPackage.getMainDocumentPart().createParagraphOfText("row2 column1"));
trGI2.getContent().add(tcGI21);

Tc tcGI22 = factory.createTc();
tcGI22.getContent().add(wordMLPackage.getMainDocumentPart().createParagraphOfText("row2 column2"));
trGI2.getContent().add(tcGI22);

tblGI.getContent().add(trGI1);
tblGI.getContent().add(trGI2);

This code shows a table with two rows. the first row has only one column and cell (which should be merged). and the second row with two cells. How do I make the 1st row be merged and will be a single cell with a column span of 2.

È stato utile?

Soluzione

You can use w:gridSpan, like so:

<w:tbl>
  <w:tblPr>
    <w:tblStyle w:val="TableGrid"/>
    <w:tblW w:w="0" w:type="auto"/>
    <w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="1" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/>
  </w:tblPr>
  <w:tblGrid>
    <w:gridCol w:w="4788"/>
    <w:gridCol w:w="4788"/>
  </w:tblGrid>
  <w:tr >
    <w:tc>
      <w:tcPr>
        <w:tcW w:w="9576" w:type="dxa"/>
        <w:gridSpan w:val="2"/>
      </w:tcPr>
      <w:p >
      </w:p>
    </w:tc>
  </w:tr>
  <w:tr >
    <w:tc>
      <w:tcPr>
        <w:tcW w:w="4788" w:type="dxa"/>
      </w:tcPr>
      <w:p />
    </w:tc>
    <w:tc>
      <w:tcPr>
        <w:tcW w:w="4788" w:type="dxa"/>
      </w:tcPr>
      <w:p />
    </w:tc>
  </w:tr>
</w:tbl>

In TcPr, there is get/setGridSpan.

ps the above XML was produced by Word 2010. You can unzip a docx to look at it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top