Java中可以使用Apache POI库来进行Excel文件的操作。下面是一个简单的示例代码,展示了如何在Java中创建并导出包含动态表头的Excel文件
public class DynamicHeaderExport {
public static void main(String[] args) throws Exception {
// 创建工作簿对象
Workbook workbook = new SXSSFWorkbook();
// 创建Sheet页
Sheet sheet = workbook.createSheet("数据");
// 设置表头内容
String[] headers = {"标题1", "标题2", "标题3"};
// 创建第一行,并将表头写入单元格
Row headerRow = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
// 自定义样式(可选)
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
cell.setCellStyle(style);
}
// 添加数据到每列
int rowNum = 1;
for (int i = 0; i < 5; i++) {
Row dataRow = sheet.createRow(rowNum++);
dataRow.createCell(0).setCellValue("USEN_NAME" + i);
dataRow.createCell(1).setCellValue("USER_PHONE" + i);
dataRow.createCell(2).setCellValue(("USER_ADDR" + i);
}
// 保存Excel文件
FileOutputStream fileOut = new FileOutputStream("dynamic_header_export.xlsx");
workbook.write(fileOut);
fileOut.close();
System.out.println("Excel文件已成功导出!");
}
}