java 从xlsx中读取数据再写回数据
时间: 2024-02-23 17:02:25 浏览: 18
可以使用Apache POI库来读取和写入Excel文件中的数据。以下是一个简单的示例代码,演示如何从一个.xlsx文件中读取数据并将其写回到同一个文件中。
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
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.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelReadWriteExample {
public static void main(String[] args) {
try {
//打开Excel文件
FileInputStream file = new FileInputStream(new File("example.xlsx"));
//创建工作簿
Workbook workbook = WorkbookFactory.create(file);
//获取第一个工作表
Sheet sheet = workbook.getSheetAt(0);
//读取数据
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
System.out.println(cell.getStringCellValue());
//写数据
row.createCell(1).setCellValue("Hello World");
//保存文件
FileOutputStream outputStream = new FileOutputStream("example.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意:在写入数据之前,需要确保Excel文件处于关闭状态。如果文件处于打开状态,写入操作将失败。