How to auto fit table and aligning the table to center, according to Word Document Size Apache-POI?

19,844

Solution 1

to set the table to auto fit , basically it's just extending the width to a specific size. example

CTTbl table        = poiTable.getCTTbl();
CTTblPr pr         = table.getTblPr();
CTTblWidth  tblW = pr.getTblW();
tblW.setW(BigInteger.valueOf(5000));
tblW.setType(STTblWidth.PCT);
pr.setTblW(tblW);
table.setTblPr(pr);

as for aligning the table to the center

CTJc jc = pr.addNewJc();        
jc.setVal(STJc.RIGHT);
pr.setJc(jc);

Solution 2

Just use "100%":

package io.github.baijifeilong.excel;

import lombok.SneakyThrows;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;

import java.io.FileOutputStream;

/**
 * Created by [email protected] at 2019-08-21 13:49
 */
public class WordDemo {

    @SneakyThrows
    public static void main(String[] args) {
        XWPFDocument document = new XWPFDocument();
        XWPFTable table = document.createTable(3, 4);
        table.setWidth("100%");
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 4; ++j) {
                table.getRow(i).getCell(j).setText(String.format("%d:%d", i + i, j + 1));
            }
        }
        document.write(new FileOutputStream("hello.docx"));
    }
}

Solution 3

To set the width of a table:

  XWPFTable table = doc.createTable(nRows, nCols);
  table.getCTTbl().addNewTblPr().addNewTblW().setW(BigInteger.valueOf(10000));

To set column width:

cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000));

If data increases in cell it effects the width of column i.e column width also will increase so to avoid this kind of problems we need to check length of string value in cell and we need to add \n (new line) in string by doing this we can set width of column.

In my project i have struggled alot to set column width and i have solved this issue by controlling data in cell.

Solution 4

You can set the width of a table in percent of the actual page size. First, get the width of the page:

CTSectPr sectPr = document.getDocument().getBody().getSectPr();
CTPageSz pageSize = sectPr.getPgSz();
double pageWidth = pageSize.getW().doubleValue();

Second step, get the margins of the page and calculate the effective page size:

CTPageMar pageMargin = sectPr.getPgMar();
double pageMarginLeft = pageMargin.getLeft().doubleValue();
double pageMarginRight = pageMargin.getRight().doubleValue();
double effectivePageWidth = pageWidth - pageMarginLeft - pageMarginRight;

Now, let's say you want the table to have a width of 60% of the effective page size. Then you calculate the size for your table. (If you want the table to fit to the actual page size, simply use 1.0):

double widthInPercent = 0.6;
int size = (int) (effectivePageWidth * widthInPercent);

Finally, set this size to your table:

CTTblWidth width = table.getCTTbl().addNewTblPr().addNewTblW();
width.setType(STTblWidth.DXA);
width.setW(new BigInteger(size + ""));

Hope this helps!

Best, Holger

Share:
19,844
Rand Mate
Author by

Rand Mate

Learning and Sharing Technical Stuffs in a friendly manner. Had basic Knowledge in C, C++ and Java... Presently Learning JAVA "What we have learnt is a mere handful; What we haven't learnt is the size of the world" "கற்றது கையளவு கல்லாதது உலகளவு...!"

Updated on July 28, 2022

Comments

  • Rand Mate
    Rand Mate almost 2 years

    How to make this table to auto-fit to document page width, when the column size increases, using apache-poi and aligning that table to center.

    This code generates a word Document extracting data from Java to word file located in c drive. I have manually set width but it now works fine. If would be valuable for me if proper guidance is provided

    public Word2Doc() throws Exception {
    
        System.out.println("This is Word To Document Class");
    
        File file = null; 
               FileOutputStream fos = null; 
               XWPFDocument document = null; 
               XWPFParagraph para = null; 
               XWPFRun run = null; 
               try { 
                   // Create the first paragraph and set it's text. 
                   document = new XWPFDocument(); 
                   para = document.createParagraph(); 
    
                   para.setAlignment(ParagraphAlignment.CENTER); 
    
                   para.setSpacingAfter(100); 
    
                   para.setSpacingAfterLines(10);
                   run = para.createRun(); 
                   for(int i=1; i<=5; i++)
                   run.setText("Test Name \009\009\009 Value \t\t\t\t Normal Ranges\013\013"); 
                   run.addBreak();    // similar to new line
                   run.addBreak();
    
                   XWPFTable table = document.createTable(4, 3);
    
                   table.setRowBandSize(1);
                   table.setWidth(1);
                   table.setColBandSize(1);
                   table.setCellMargins(1, 1, 100, 30);
    
                   table.setStyleID("finest");
    
    
                   table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE");
                   table.getRow(2).getCell(1).setText("fine");
                   XWPFParagraph p1 = table.getRow(0).getCell(0).getParagraphs().get(0);
                   p1.setAlignment(ParagraphAlignment.CENTER);
                           XWPFRun r1 = p1.createRun();
                           r1.setBold(true);
                           r1.setText("Test Name");
                           r1.setItalic(true);
                           r1.setFontFamily("Courier");
                           r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
                           r1.setTextPosition(100);
    
                  //Locating the cell values
                            table.getRow(0).getCell(1).setText("Value"); 
                            table.getRow(0).getCell(2).setText("Normal Ranges"); 
    
                           table.getRow(2).getCell(2).setText("numeric values");
    
                            table.setWidth(120);
    
                   file = new File("c:\\nwhpe.docx"); 
                   if(file.exists())
                       file.delete();
    
    
                   FileOutputStream out = new FileOutputStream(file);
                   document.write(out);
                   out.close();
               } 
    
           } 
    public static void main(String ar[]) throws Exception{
        new Word2Doc();
    }
    

    }

  • golimar
    golimar about 6 years
    What are the units? (i.e. what does 2000 and 10000 mean?)
  • EverNight
    EverNight almost 6 years
    A better alternative should be found. This results in unpredictable table sizes based on the content present in the page.
  • Till F.
    Till F. over 4 years
    i can confirm: with apache poi 4.1.1 it is possible to set the table width in percent.
  • ezwrighter
    ezwrighter almost 4 years
    Yes, in Apache POI > 4.0.0 table.setWidth(String) is available - poi.apache.org/apidocs/dev/org/apache/poi/xwpf/usermodel/…