Auto port to apache POI (Excel)

I have a java program that takes header and data as input and creates an excel file.

However, sometimes when the header values โ€‹โ€‹are long and the number of columns is larger, my excel sheet tends to be overly wide.

Due to the headings, I will have to scroll to the right to see the contents of the end columns.

Is there a way to resolve this so that if the content in the cell is larger, then say x, then the automatic hyphenation will automatically end, and the row height will automatically increase, and the column width will be fixed.

A rough algorithm for what I'm looking for:

 if(content.size is more then 50 chars){
       - apply auto wrap with centred text
       - adjust the row height accordingly
       - adjust all the cells in the column accordingly
 }

If someone can point me to some example available on the Internet.

Thanks for reading!

+4
1

, , :

public class SO{
    public static void main(String[] args) {

        try {
            FileInputStream is = new FileInputStream(new File("D:\\Users\\user2777005\\Desktop\\bob.xlsx"));
            XSSFWorkbook wb = new XSSFWorkbook(is);
            String header = "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789";
            Sheet sheet = wb.getSheet("Sheet1");
            sheet.setColumnWidth(0, 18000);
            Row row = sheet.createRow(0);
            Cell cell = row.createCell(0);

            if(header.length() > 50){ //Length of String for my test
                sheet.setColumnWidth(0, 18000); //Set column width, you'll probably want to tweak the second int
                CellStyle style = wb.createCellStyle(); //Create new style
                style.setWrapText(true); //Set wordwrap
                cell.setCellStyle(style); //Apply style to cell
                cell.setCellValue(header); //Write header
            }

            wb.write(new FileOutputStream(new File("D:\\Users\\user2777005\\Desktop\\bob.xlsx")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}       

!

+30

All Articles