java POI实现 读取两个excel表,把相同名字的数据的某些列进行差异对比
时间: 2024-03-16 22:41:07 浏览: 91
好的,下面是使用POI库实现读取两个Excel表并比较相同名字数据的某些列进行差异对比的示例代码:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
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;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelCompare {
public static void main(String[] args) throws Exception {
// 读取第一个Excel表
FileInputStream file1 = new FileInputStream("file1.xlsx");
Workbook workbook1 = WorkbookFactory.create(file1);
Sheet sheet1 = workbook1.getSheetAt(0);
// 读取第二个Excel表
FileInputStream file2 = new FileInputStream("file2.xlsx");
Workbook workbook2 = WorkbookFactory.create(file2);
Sheet sheet2 = workbook2.getSheetAt(0);
// 存储第一个Excel表中的数据
Map<String, String[]> data1 = new HashMap<String, String[]>();
Iterator<Row> rowIterator1 = sheet1.iterator();
while (rowIterator1.hasNext()) {
Row row = rowIterator1.next();
String[] rowData = new String[]{row.getCell(1).getStringCellValue(), row.getCell(2).getStringCellValue()};
data1.put(row.getCell(0).getStringCellValue(), rowData);
}
// 比较第二个Excel表中的数据
XSSFWorkbook resultWorkbook = new XSSFWorkbook();
XSSFSheet resultSheet = resultWorkbook.createSheet("Sheet1");
XSSFCellStyle style = resultWorkbook.createCellStyle();
XSSFFont font = resultWorkbook.createFont();
font.setBold(true);
style.setFont(font);
int row = 0;
Iterator<Row> rowIterator2 = sheet2.iterator();
while (rowIterator2.hasNext()) {
Row row2 = rowIterator2.next();
String name = row2.getCell(0).getStringCellValue();
if (data1.containsKey(name)) {
String[] rowData1 = data1.get(name);
String[] rowData2 = new String[]{row2.getCell(1).getStringCellValue(), row2.getCell(2).getStringCellValue()};
// 进行某些列的差异对比
if (!rowData1[0].equals(rowData2[0])) {
XSSFRow resultRow = resultSheet.createRow(row++);
resultRow.createCell(0).setCellValue(name);
resultRow.createCell(1).setCellValue(rowData1[0]);
resultRow.createCell(2).setCellValue(rowData2[0]);
resultRow.getCell(0).setCellStyle(style);
resultRow.getCell(1).setCellStyle(style);
resultRow.getCell(2).setCellStyle(style);
}
}
}
// 保存结果文件
FileOutputStream fileOut = new FileOutputStream("result.xlsx");
resultWorkbook.write(fileOut);
fileOut.close();
resultWorkbook.close();
// 关闭文件
file1.close();
file2.close();
}
}
```
此示例代码使用了POI库来读取Excel文件,它支持读取和写入.xls和.xlsx格式的Excel文件,可以根据具体需求进行选择。注意,还需要在项目中添加POI库的依赖。此外,示例代码仅用于演示目的,实际应用程序需要根据具体要求进行更改和完善。
阅读全文