21xrx.com
2025-04-02 21:43:14 Wednesday
文章检索 我的文章 写文章
如何使用Java导出Excel表格
2023-06-11 05:23:18 深夜i     20     0
Java Excel 导出

我最近在写一个Java项目,其中有个功能是要将数据导出到Excel表格中。我使用了Apache POI这个强大的Java库来实现这个功能。下面是我写的代码例子:

// 创建Excel文档
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
// 创建表头
Row headerRow = sheet.createRow(0);
Cell cell = headerRow.createCell(0);
cell.setCellValue("Name");
cell = headerRow.createCell(1);
cell.setCellValue("Age");
cell = headerRow.createCell(2);
cell.setCellValue("Gender");
// 填入数据
Row dataRow = sheet.createRow(1);
cell = dataRow.createCell(0);
cell.setCellValue("Tom");
cell = dataRow.createCell(1);
cell.setCellValue(28);
cell = dataRow.createCell(2);
cell.setCellValue("Male");
// 输出到文件
FileOutputStream output = new FileOutputStream("output.xlsx");
workbook.write(output);
// 关闭资源
output.close();
workbook.close();

  
  

评论区