java后台生成excel全局宽度边框样式设置
时间: 2023-08-16 11:06:38 浏览: 50
要在Java后台中生成Excel文件并设置全局宽度和边框样式,可以使用Apache POI库来完成。以下是一个简单的示例代码:
```java
// 创建工作簿对象
Workbook workbook = new XSSFWorkbook();
// 创建工作表对象
Sheet sheet = workbook.createSheet("Sheet1");
// 设置列宽
sheet.setColumnWidth(0, 5000); // 第1列宽度为5000
sheet.setColumnWidth(1, 8000); // 第2列宽度为8000
sheet.setDefaultColumnWidth(10); // 其他列默认宽度为10
// 创建单元格样式对象
CellStyle style = workbook.createCellStyle();
style.setBorderTop(BorderStyle.THIN); // 上边框样式
style.setBorderBottom(BorderStyle.THIN); // 下边框样式
style.setBorderLeft(BorderStyle.THIN); // 左边框样式
style.setBorderRight(BorderStyle.THIN); // 右边框样式
// 创建标题行
Row titleRow = sheet.createRow(0);
titleRow.createCell(0).setCellValue("标题1");
titleRow.createCell(1).setCellValue("标题2");
// 设置标题行样式
for (Cell cell : titleRow) {
cell.setCellStyle(style);
}
// 创建数据行
for (int i = 1; i <= 10; i++) {
Row dataRow = sheet.createRow(i);
dataRow.createCell(0).setCellValue("数据" + i + "-1");
dataRow.createCell(1).setCellValue("数据" + i + "-2");
// 设置数据行样式
for (Cell cell : dataRow) {
cell.setCellStyle(style);
}
}
// 输出Excel文件
FileOutputStream outputStream = new FileOutputStream("output.xlsx");
workbook.write(outputStream);
outputStream.close();
```
这段代码创建了一个名为`Sheet1`的工作表,并设置了第1列宽度为5000,第2列宽度为8000,其他列默认宽度为10。同时,创建了一个单元格样式对象,设置了上下左右四个边框的样式为细线。然后创建了一个标题行和10行数据行,并给它们设置了相同的样式。最后将工作簿对象输出到文件中。