java 合并excel
时间: 2023-09-18 07:07:22 浏览: 75
Java可以使用Apache POI库来操作Excel文件,包括合并多个Excel文件。
以下是一个示例代码,使用POI库来合并两个Excel文件:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ExcelMerger {
public static void main(String[] args) throws Exception {
// 读取第一个Excel文件
FileInputStream fileInputStream1 = new FileInputStream(new File("file1.xls"));
HSSFWorkbook workbook1 = new HSSFWorkbook(fileInputStream1);
HSSFSheet sheet1 = workbook1.getSheetAt(0);
// 读取第二个Excel文件
FileInputStream fileInputStream2 = new FileInputStream(new File("file2.xls"));
HSSFWorkbook workbook2 = new HSSFWorkbook(fileInputStream2);
HSSFSheet sheet2 = workbook2.getSheetAt(0);
// 合并两个Excel文件
List<Row> rows = new ArrayList<Row>();
Iterator<Row> rowIterator = sheet1.iterator();
while (rowIterator.hasNext()) {
rows.add(rowIterator.next());
}
rowIterator = sheet2.iterator();
while (rowIterator.hasNext()) {
rows.add(rowIterator.next());
}
// 创建新的Excel文件
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("merged");
// 将合并的行写入新的Excel文件
int rowIndex = 0;
for (Row row : rows) {
HSSFRow newRow = sheet.createRow(rowIndex++);
int cellIndex = 0;
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
newRow.createCell(cellIndex++).setCellValue(cell.getStringCellValue());
}
}
// 保存新的Excel文件
FileOutputStream fileOutputStream = new FileOutputStream(new File("merged.xls"));
workbook.write(fileOutputStream);
fileOutputStream.close();
}
}
```
这个示例代码将`file1.xls`和`file2.xls`两个Excel文件合并为一个新的Excel文件`merged.xls`,新的Excel文件只包含第一个sheet的数据。
阅读全文