lucifer lucifer - 1 month ago 16
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");
r3.setBold(true);



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

//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(1).setText("Client");
table.getRow(2).getCell(2).setText("Carnival Corporation");

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

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

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

width.setType(STTblWidth.DXA);
width.setW(BigInteger.valueOf(1500));


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

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:

table.getRow(0).getCell(0).getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000));

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);

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

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

Comments