'Apache Poi: Overflowing Text

I'm using apache poi 4.1.2 to write an xlsx file.

I would like to be sure that every text overflows its cell. The image shows the desired result.

My code:

package poisamples;

import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class XSSFTxt {

  public static void main(String[] args) throws IOException {
    String txt = "Random txt, random txt, random txt";
    String outputFile = "exampleFileTxt.xlsx";
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Txt");

    sheet.setColumnWidth(1, 15);
    Row row = sheet.getRow(1);
    if (row == null) {
      row = sheet.createRow(1);
    }
    Cell cell = row.getCell(1);
    if (cell == null) {
      cell = row.createCell(1);
    }
    CellStyle newCellStyle = workbook.createCellStyle();
    newCellStyle.setWrapText(true);
    cell.setCellStyle(newCellStyle);
    cell.setCellValue(txt);

    try {
      FileOutputStream fos = new FileOutputStream(outputFile);
      workbook.write(fos);
      fos.close();
    }
    catch (IOException ioe) {
      System.out.println("Error");
    }
    workbook.close();
  }
}

Desired result

I'm looking at the documentation, but I can't find anything to help me. Any tip?



Solution 1:[1]

As documented in Sheet.setColumnWidth, it sets the width in units of 1/256th of a character width. So a width of 256 means a width of one character. Your width of 15 is too small. So the column has a effective width of 0 characters and is hidden.

So do

...
sheet.setColumnWidth(1, 256);
...

in your code.

Moreover the setting of CellStyle.setWrapText(true) means all content is visible within this cell by displaying it on multiple lines. This is the exact opposite of overflow the cell border. So if you want it to overflow the cell border, don't set wrap text true.

...
CellStyle newCellStyle = workbook.createCellStyle();
//newCellStyle.setWrapText(true);
cell.setCellStyle(newCellStyle);
...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1