Java读取本地excel文件数据 部分数据写入本地另一个excel文件
时间: 2025-01-25 21:09:11 浏览: 33
在Java中读取本地Excel文件的数据并将部分数据写入另一个本地Excel文件,通常可以使用Apache POI库。以下是一个简单的示例,演示如何实现这一功能。
首先,确保你已经在项目中引入了Apache POI库。如果你使用Maven,可以在`pom.xml`中添加以下依赖:
```xml
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
</dependencies>
```
然后,你可以使用以下代码来读取一个Excel文件并将部分数据写入另一个Excel文件:
```java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
public class ExcelReadWriteExample {
public static void main(String[] args) {
String inputFilePath = "input.xlsx";
String outputFilePath = "output.xlsx";
try (FileInputStream inputStream = new FileInputStream(inputFilePath);
Workbook inputWorkbook = new XSSFWorkbook(inputStream);
FileOutputStream outputStream = new FileOutputStream(outputFilePath);
Workbook outputWorkbook = new XSSFWorkbook()) {
Sheet inputSheet = inputWorkbook.getSheetAt(0);
Sheet outputSheet = outputWorkbook.createSheet("FilteredData");
for (Row row : inputSheet) {
// 假设我们只复制第一列不为空的数据
Cell cell = row.getCell(0);
if (cell != null && cell.getCellType() != CellType.BLANK) {
Row newRow = outputSheet.createRow(outputSheet.getLastRowNum() + 1);
Cell newCell = newRow.createCell(0);
newCell.setCellValue(cell.getStringCellValue());
}
}
outputWorkbook.write(outputStream);
System.out.println("Data written to " + outputFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个示例中,我们首先读取名为`input.xlsx`的Excel文件,然后创建一个新的Excel文件`output.xlsx`。在读取输入文件的过程中,我们只将第一列不为空的数据写入输出文件。
阅读全文
相关推荐

















