java生成excel
时间: 2023-09-12 13:03:05 浏览: 38
Java可以使用Apache POI库生成Excel文件。以下是一个简单的示例,演示如何创建一个Excel文件并向其中添加数据:
```java
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelGenerator {
public static void main(String[] args) {
// 创建工作簿对象
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建工作表对象
Sheet sheet = workbook.createSheet("Sheet1");
// 创建标题行
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("姓名");
cell = row.createCell(1);
cell.setCellValue("年龄");
cell = row.createCell(2);
cell.setCellValue("性别");
// 添加数据行
row = sheet.createRow(1);
cell = row.createCell(0);
cell.setCellValue("张三");
cell = row.createCell(1);
cell.setCellValue(18);
cell = row.createCell(2);
cell.setCellValue("男");
row = sheet.createRow(2);
cell = row.createCell(0);
cell.setCellValue("李四");
cell = row.createCell(1);
cell.setCellValue(22);
cell = row.createCell(2);
cell.setCellValue("女");
// 输出Excel文件
try (FileOutputStream outputStream = new FileOutputStream("output.xlsx")) {
workbook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
该示例使用XSSF(XML Spreadsheet Format)格式生成Excel文件。如果需要生成早期版本的Excel文件,可以使用HSSF(Horrible Spreadsheet Format)格式。