java1.8读写excel表格
时间: 2024-09-23 18:05:20 浏览: 47
Java导出excel表格
在Java 1.8版本中,虽然标准库并不直接支持读写Excel文件,但是可以借助第三方库如Apache POI来方便地操作Excel。Apache POI是一个功能强大的API,它提供了HSSF(处理旧版的Excel .xls文件)和XSSF(用于新版本.xlsx文件)两个组件。
以下是基本步骤:
1. **添加依赖**:
- 在Maven项目中,在pom.xml中添加POI依赖:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
2. **读取Excel**:
- 使用`HSSFWorkbook`或`XSSFWorkbook`加载.xls或.xlsx文件:
```java
FileInputStream fis = new FileInputStream("example.xlsx");
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String value = cell.getStringCellValue();
System.out.print(value + "\t");
}
System.out.println();
}
workbook.close();
```
3. **写入Excel**:
- 创建一个新的`XSSFWorkbook`实例,并创建一个工作表,然后添加行和单元格:
```java
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello World");
FileOutputStream fos = new FileOutputStream("output.xlsx");
workbook.write(fos);
fos.close();
workbook.close();
```
阅读全文