判断2个excel文件差异的条数
判断2个excel文件差异的条数
package com.lucky.luckydoc;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExcelComparator {
public static void main(String[] args) throws IOException {
String file1Path = "C:\\Users\\luckincoffee\\Downloads\\DBSearch_2024-09-14_10_59_36.xlsx";
String file2Path = "C:\\Users\\luckincoffee\\Downloads\\DBSearch_2024-09-14_11_00_03.xlsx";
// 读取两个 Excel 文件
List<List<String>> file1Data = readExcel(file1Path);
List<List<String>> file2Data = readExcel(file2Path);
// 比较两个文件的差异
compareExcelRows(file1Data, file2Data);
}
// 读取 Excel 文件中的数据
public static List<List<String>> readExcel(String filePath) throws IOException {
List<List<String>> data = new ArrayList<>();
FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
for (Row row : sheet) {
List<String> rowData = new ArrayList<>();
for (Cell cell : row) {
rowData.add(getCellValueAsString(cell));
}
data.add(rowData);
}
workbook.close();
fis.close();
return data;
}
// 根据单元格的类型获取字符串形式的值
public static String getCellValueAsString(Cell cell) {
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue(); // 字符串类型
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
// 如果是日期类型,返回日期格式
return cell.getDateCellValue().toString();
} else {
// 否则返回数值类型
return String.valueOf(cell.getNumericCellValue());
}
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue()); // 布尔类型
case FORMULA:
return cell.getCellFormula(); // 公式类型
case BLANK:
return ""; // 空白单元格
default:
return "未知类型";
}
}
// 比较两个 Excel 文件的行差异
public static void compareExcelRows(List<List<String>> file1Data, List<List<String>> file2Data) {
int maxRows = Math.max(file1Data.size(), file2Data.size());
List<List<String>> result = new ArrayList<>();
if(file1Data.size()>file2Data.size()){
file1Data.removeAll(file2Data);
result=file1Data;
}else if(file2Data.size()>file1Data.size()){
file2Data.removeAll(file1Data);
result=file2Data;
}
for (List<String> row : result){
System.out.println(row);
}
// for (int i = 0; i < maxRows; i++) {
// List<String> row1 = i < file1Data.size() ? file1Data.get(i) : new ArrayList<>();
// List<String> row2 = i < file2Data.size() ? file2Data.get(i) : new ArrayList<>();
//
// if (!row1.equals(row2)) {
// System.out.println("第 " + (i + 1) + " 行不同:");
// System.out.println("文件1: " + row1);
// System.out.println("文件2: " + row2);
// }
// }
}
}