XSSFWorkbook设置边框
时间: 2024-01-12 09:14:25 浏览: 32
要在使用Apache POI库的XSSFWorkbook对象中设置边框,您可以使用CellStyle和Font类来实现。以下是一个示例代码,演示如何设置单元格的边框:
```java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class SetBorderExample {
public static void main(String[] args) {
// 创建工作簿和工作表
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
// 创建单元格样式
CellStyle style = workbook.createCellStyle();
style.setBorderTop(BorderStyle.THIN);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
// 创建字体样式
Font font = workbook.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 12);
// 将字体样式应用于单元格样式
style.setFont(font);
// 创建单元格并设置样式
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello");
cell.setCellStyle(style);
// 保存工作簿
try {
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
System.out.println("工作簿保存成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码创建了一个带有边框的单元格,并将工作簿保存为名为"workbook.xlsx"的文件。可以根据需要调整边框的样式和单元格位置,具体的边框样式可以通过设置BorderSize、BorderStyle和BorderColor等属性来实现。