lucifer lucifer - 11 months ago 102
Apache Configuration Question

How to format cell in XWPFTable in Apache POI

I am able to create a table in Apache POI in word ,my table is coming with proper value but what i want i want to decrease the cell size of the column size in the table how to do that ,please help..Here is what i have done upto

XWPFTable table = document.createTable(5,3);

r3.setText("MSH Activity Score Card");

//creating first row
table.getRow(0).getCell(1).setText("Job ID#");

//creating second row

table.getRow(1).getCell(1).setText("Job Title#");
table.getRow(1).getCell(2).setText("Global Network Architect Consultant");

//creating third row
table.getRow(2).getCell(2).setText("Carnival Corporation");

//creating fourth row
table.getRow(3).getCell(1).setText("Start Date");

//creating fifth row
table.getRow(4).getCell(1).setText("Days Old");

CTTblWidth width = table.getCTTbl().addNewTblPr().addNewTblW();


I am getting a table with data but i want to minimize the size enter image description here

But i want this sizeenter image description here

Answer Source

First you need to make sure that you've declared the library's imports :

import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

Then it's just like , assuming you want to format cell-0 on row-0:


Or put this snippet after creating your last row to format all cells:

for(int x = 0;x < table.getNumberOfRows(); x++){
          XWPFTableRow row = table.getRow(x);
          int numberOfCell = row.getTableCells().size();
          for(int y = 0; y < numberOfCell ; y++){
              XWPFTableCell cell = row.getCell(y);


*But remember that the width of the cell will always increase to follow the length of the string.