Search code examples
javaapache-poixssf

Java Apache POI Excel set border on specific cell and set currency cell format


I am working to generate excel using java apache poi i just need to beautify it (with border)

below is the excel that i have successfuly create excel

and here is the excel that i wanted (see those border and currency and background color) enter image description here

heres some of my code to generate the excel

Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("sheet1");
Row row = sheet.createRow(rowIndex);
row.createCell(0).setCellValue("Product Name");
row.createCell(1).setCellValue("name");

FileOutputStream fileOut = new FileOutputStream("excel.xlsx");
workbook.write(fileOut);
fileOut.flush();
fileOut.close();

Solution

  • I assume you'd need to break down the creation of your cell in this format first before applying any style onto it:

                        Cell cell1 = row.createCell(0);
                        cell1.setCellValue("Product Name");
    

    Later,

            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setBorderTop((short) 1); // single line border
            cellStyle.setBorderBottom((short) 1); // single line border
            ...//add many others here
            cell1.setCellStyle(cellStyle); //apply that style to the cell
    

    Simple way is to create a cellStyle at first and then just go ahead with numerous cell creations as per the application requirement! Next, just loop into each cell to apply the cellStyle if it is a common behavior that you need for all. Hope that helps!