Apache POI 表格:如何设置表头边框
在 Apache POI 中,可以通过设置表格样式来为表头设置边框。以下是一个示例代码:
// 创建工作簿和工作表
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet('Sheet1');
// 创建表头行
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue('Header 1');
headerRow.createCell(1).setCellValue('Header 2');
headerRow.createCell(2).setCellValue('Header 3');
// 创建表格样式
CellStyle style = workbook.createCellStyle();
style.setBorderTop(BorderStyle.THIN);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
// 设置表头单元格的样式
for (Cell cell : headerRow) {
cell.setCellStyle(style);
}
// 写入数据并保存文件
FileOutputStream fileOut = new FileOutputStream('workbook.xlsx');
workbook.write(fileOut);
fileOut.close();
workbook.close();
在上面的代码中,我们使用 setBorderXXX 方法设置了表格样式的边框属性。然后,我们将这个样式应用到表头单元格中,以此来为表头设置边框。最后,我们将数据写入工作簿并保存。
原文地址: https://www.cveoy.top/t/topic/nWHm 著作权归作者所有。请勿转载和采集!