Java Apache POI Excel 在特定单元格上设置边框并设置货币单元格格式

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

我正在使用 java apache poi 生成 excel 我只需要美化它(带边框)

下面是我成功创建的 excel

这是我想要的 excel(请参阅那些边框和货币以及背景颜色)

这是我生成 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();

我假设您需要先分解以这种格式创建的单元格,然后再对其应用任何样式:

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

稍后,

        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

简单的方法是先创建一个cellStyle,然后根据应用程序的要求继续创建多个单元格!接下来,只需循环到每个单元格以应用 cellStyle,如果它是您需要的所有常见行为。 希望对您有所帮助!