java - 如何使用java从e​​xcel中获取重复记录并写入新文件

标签 java excel duplicates apache-poi

我可以使用下面的代码读取第0列的数据。我需要获取第 0 列中存在的重复值的记录

FileInputStream fis = new FileInputStream(theNewestFile);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
XSSFRow row;
String cellValueMaybeNull;
List<Cell> cells = new ArrayList<Cell>();

for (int rowIndex = 0; rowIndex <= spreadsheet.getLastRowNum(); rowIndex++) {
    row = (XSSFRow) spreadsheet.getRow(rowIndex);
    if (row != null) {
        int colIndex = 0;
        Cell cell = row.getCell(colIndex);
        if (cell != null) {
            // Found column and there is value in the cell.
            cellValueMaybeNull = cell.getStringCellValue();
            // Do something with the cellValueMaybeNull here ...
            System.out.println(cellValueMaybeNull);

        }
    }
} 

最佳答案

声明一个 Map 并捕获所有重复项并稍后打印。如果列表大小大于 1,则为重复情况。

FileInputStream fis = new FileInputStream(theNewestFile);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
XSSFRow row;
String cellValueMaybeNull;
List<Cell> cells = new ArrayList<Cell>();

Map<String,List<String>> duplicateCheck = new HashMap<String,List<String>>();
for (int rowIndex = 0; rowIndex <= spreadsheet.getLastRowNum(); rowIndex++) {
         row = (XSSFRow) spreadsheet.getRow(rowIndex);
         if (row != null) {
           int colIndex = 0;
           Cell cell = row.getCell(colIndex);
           if (cell != null) {
           // Found column and there is value in the cell.
           cellValueMaybeNull = cell.getStringCellValue();
           // Do something with the cellValueMaybeNull here ...
           if(duplicateCheck.get(cellValueMaybeNull) != null) {
                 duplicateCheck.get(cellValueMaybeNull).add(cellValueMaybeNull);
           }
           else {
           List<String> list = new ArrayList<String>();
               list.add(cellValueMaybeNull);
               duplicateCheck.put(cellValueMaybeNull, list);
            }

               }
            }
        } 

for(List<String> duplicateValue : duplicateCheck.values()) {
            if(duplicateValue.size() > 1) {
                System.out.println("Duplicate values :"+duplicateValue);
            }
        }

关于java - 如何使用java从e​​xcel中获取重复记录并写入新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57723940/

相关文章:

java - 我不明白为什么这里抛出 ArrayIndexOutOfBoundsException

java - 从@ElementCollection 中搜索一个对象

java - 从表达式树递归创建完全括号表达式的算法

java - 如何让 Watson Conversation Api 在用户输入时调用 Web 应用程序 Url?

javascript - 检查 DOM 中的重复链接

vba - 格式化(动态)

excel - 从 Excel 到 Word 表格中的特定单元格

excel - While-loop 使 Excel 崩溃

php - Yii 中的 AR 添加重复行

mysql - 从 MySQL 表中删除两个字段相同的重复项