我最近用 java 完成了一个项目,用于比较 2 个不同文件夹中的 Excel 工作表,并在源文件夹目录中创建的摘要文件夹中生成结果。除了超过 10000 行的文件外,所有代码都工作正常。它只是创建一个空表,而不是比较较大文件的不匹配情况。这是我使用的代码请帮助我。
package com.validation.comparators;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
/**
* The utility class SheetComparator
*/
public class SheetComparator {
private SheetComparator() {
// The utility class
}
/**
* Compares the document equivalent of two sheets
*
* @param document1
* The document 1
* @param document2
* The document 2
* @return The compared output
*/
@SuppressWarnings("unchecked")
public static Document compare(Document document1, Document document2) {
List<String> headers = (List<String>) document1.get("headers");
List<Document> sheet1Rows = (List<Document>) document1.get("data");
List<Document> sheet2Rows = (List<Document>) document2.get("data");
List<Document> temp;
List<Document> comparedOutput = new ArrayList<>();
if (sheet1Rows.size() < sheet2Rows.size()) {
temp = sheet1Rows;
sheet1Rows = sheet2Rows;
sheet2Rows = temp;
}
int length = sheet1Rows.size();
int length2 = sheet2Rows.size();
for (int i = 0; i < length2; i++) {
Document sheet1Row = sheet1Rows.get(i);
Document sheet2Row = sheet2Rows.get(i);
Document comparedRow = new Document("row number",
new Document("value", sheet1Row.getString("row number")).append("color", "WHITE"));
Boolean completeMatch = true;
for (String header : headers) {
Boolean isNull = false;
String value1 = sheet1Row.getString(header).trim();
String value2 = sheet2Row.getString(header).trim();
if (StringUtils.isAnyBlank(value1, value2)) {
completeMatch = false;
isNull = true;
} else if (!StringUtils.equals(value1, value2)) {
completeMatch = false;
}
if (isNull) {
comparedRow.append(header, new Document("value", StringUtils.isBlank(value1) ? value2 : value1)
.append("color", "RED"));
} else {
comparedRow.append(header, new Document("value", value1).append("color", "WHITE"));
}
}
if (!completeMatch) {
comparedOutput.add(comparedRow);
}
}
for (int i = length2; i < length; i++) {
Document row = sheet1Rows.get(i);
Document comparedRow = new Document();
for (String header : headers) {
String value = row.getString(header);
comparedRow.put(header, new Document("value", value).append("color", "RED"));
}
comparedRow.append("row number",
new Document("value", row.getString("row number")).append("color", "WHITE"));
comparedOutput.add(comparedRow);
}
headers.add(0, "row number");
return new Document("data", comparedOutput).append("headers", headers);
}
}
最佳答案
尝试一下,将 jvm (java) 内存设置得较高。问题是您必须读取整个 DOM 对象层次结构。
否则您只需按表、按行、按单元格顺序读取文档。 因此,您可以:
,而不是在内存中保留一些 DOM 对象- 将文档的顺序流(作为文本文档)写入文件。
- 将两个 Excel 转换为文本。
- 读取两个流并对每个标记进行比较。
- 也许您可以立即编写差异报告。
关于用于比较 Excel 工作表的 Java 代码不适用于较大的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58005311/