java导出excel横纵表头怎么设置
时间: 2023-09-22 17:11:53 浏览: 94
在Java中导出Excel并设置横纵表头可以使用Apache POI库。以下是示例代码:
```
// 创建工作簿
Workbook workbook = new HSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("Sheet1");
// 创建表头行
Row headerRow = sheet.createRow(0);
// 创建表头单元格,并设置值
Cell headerCell1 = headerRow.createCell(0);
headerCell1.setCellValue("姓名");
Cell headerCell2 = headerRow.createCell(1);
headerCell2.setCellValue("语文");
Cell headerCell3 = headerRow.createCell(2);
headerCell3.setCellValue("数学");
Cell headerCell4 = headerRow.createCell(3);
headerCell4.setCellValue("英语");
// 创建数据行
Row dataRow1 = sheet.createRow(1);
// 创建姓名单元格,并设置值
Cell nameCell1 = dataRow1.createCell(0);
nameCell1.setCellValue("张三");
// 创建成绩单元格,并设置值
Cell scoreCell1 = dataRow1.createCell(1);
scoreCell1.setCellValue(80);
Cell scoreCell2 = dataRow1.createCell(2);
scoreCell2.setCellValue(90);
Cell scoreCell3 = dataRow1.createCell(3);
scoreCell3.setCellValue(85);
// 创建数据行
Row dataRow2 = sheet.createRow(2);
// 创建姓名单元格,并设置值
Cell nameCell2 = dataRow2.createCell(0);
nameCell2.setCellValue("李四");
// 创建成绩单元格,并设置值
Cell scoreCell4 = dataRow2.createCell(1);
scoreCell4.setCellValue(75);
Cell scoreCell5 = dataRow2.createCell(2);
scoreCell5.setCellValue(85);
Cell scoreCell6 = dataRow2.createCell(3);
scoreCell6.setCellValue(90);
// 设置表头行和表格数据行的单元格样式
CellStyle headerCellStyle = workbook.createCellStyle();
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerCellStyle.setFont(headerFont);
CellStyle dataCellStyle = workbook.createCellStyle();
Font dataFont = workbook.createFont();
dataCellStyle.setFont(dataFont);
// 设置每列的列宽
sheet.setColumnWidth(0, 4000);
sheet.setColumnWidth(1, 3000);
sheet.setColumnWidth(2, 3000);
sheet.setColumnWidth(3, 3000);
// 导出Excel文件
FileOutputStream outputStream = new FileOutputStream("test.xls");
workbook.write(outputStream);
outputStream.close();
```
在上面的示例代码中,通过`sheet.createRow()`方法创建行,通过`row.createCell()`方法创建单元格,并设置单元格的值。其中第一行为表头行,后面的行为数据行。通过`workbook.createCellStyle()`方法和`workbook.createFont()`方法创建样式和字体,然后将样式应用到表头行和数据行的单元格上。最后通过`sheet.setColumnWidth()`方法设置每列的列宽,并通过`workbook.write()`方法将工作簿导出为Excel文件。
阅读全文
相关推荐

















