简体   繁体   English

比较不同文件(CSV,Excel)中两列的日期Java Apache commons和poi以了解日期相似的位置

[英]Comparing between dates of two columns in different files (CSV, Excel) Java Apache commons and poi to know where the dates are similar

I have an Excel and a CSV File. 我有一个Excel和一个CSV文件。 The two files contain dates in their first columns. 这两个文件的第一列包含日期。

I want to compare these dates and look where are they the same, like to get true in the big excel file. 我想比较这些日期,看看它们在哪里相同,就像在大的excel文件中得到真实一样。 But I am having problems with the date format difference between the two files. 但我遇到两个文件之间的日期格式差异的问题。

I simply want java to know where these dates are similar, so i can update later on the excel file with values from the exported CSV File. 我只是想让java知道这些日期的相似之处,所以我可以稍后使用导出的CSV文件中的值更新excel文件。

Link to the two files: https://1drv.ms/f/s!AphATk_r_LQkl0HBC2r_9nt_AYIg 链接到两个文件: https//1drv.ms/f/s!AphATk_r_LQkl0HBC2r_9nt_AYIg

My Code yet: 我的代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CsvToExcelConverter {

    public static final String SAMPLE_XLSX_FILE_PATH = "C:/Users/blawand/Desktop/CSV_to_Excel/export-excel-test.xlsx";
    public static final String SAMPLE_CSV_FILE_PATH = "C:/Users/blawand/Desktop/CSV_to_Excel/export-csv-test.csv";
    public static List<String> dates_csv = new ArrayList<>();
    public static List<String> dates_excel = new ArrayList<>();

    public static void main(String[] args) throws IOException, InvalidFormatException {

        try (Reader reader = Files.newBufferedReader(Paths.get(SAMPLE_CSV_FILE_PATH));
                CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);) {

            for (CSVRecord csvRecord : csvParser) {
                // Accessing Values by Column Index
                String name = csvRecord.get(0);
                dates_csv.add(name);
            }

            dates_csv.remove(0);
        }

        FileInputStream fsIP = new FileInputStream(new File(SAMPLE_XLSX_FILE_PATH));

        /*
         * ================================================================== 
         * Iterating
         * over all the rows and columns in a Sheet (Multiple ways)
         * ==================================================================
         */

        // Getting the Sheet at index zero
        XSSFWorkbook workbook = new XSSFWorkbook(fsIP);
        XSSFSheet sheet = workbook.getSheetAt(0);
        DataFormatter dataFormatter = new DataFormatter();

        for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
            Row row = sheet.getRow(rowIndex);
            if (row != null) {
                Cell cell = row.getCell(0); // getColumn(0)
                if (cell != null) {
                    // Found column and there is value in the cell.
                    // String cellValueMaybeNull = cell.getStringCellValue();
                    String cellValueMaybeNull = dataFormatter.formatCellValue(cell);

                    // String to number set
                    dates_excel.add(cellValueMaybeNull);

                }
            }
        }

        System.out.println(dates_csv);
        System.out.println(dates_csv.size());
        System.out.println(dates_excel);
        System.out.println(dates_excel.size());

        while (dates_excel == dates_excel) {
            System.out.println("Yes");
            break;
        }

        fsIP.close();
        FileOutputStream output_file = new FileOutputStream(new File(SAMPLE_XLSX_FILE_PATH));
        workbook.write(output_file);
        output_file.close();

    }
}

What would you like to know more? 您还想了解更多? please ask me! 请问我! I would be very thankful 我会非常感激

Comparing dates for equality may be done by re-formatting and comparing the String s themselves or parsing those String s to LocalDate s and comparing those. 比较相等的日期可以通过重新格式化和比较String本身或将这些String解析为LocalDate并进行比较来完成。

First option would be re-formatting one String to make it have the same formatting as the other one, but both stay String s. 第一个选项是重新格式化一个String ,使其具有与另一个相同的格式,但两者都保留String

The second possibility is creating a modern time representation out of both and compare them by the built-in comparison of this representation. 第二种可能性是从两者中创建一个现代时间表示,并通过该表示的内置比较来比较它们。

public class TryOutClass {

    /**
     * Compares two dates and checks if they are equal using {@link String} comparison.
     * <p>
     * <strong>Important note:</strong><br>
     * This assumes the first date given is of the format "EEE, dd/MM/yy" and 
     * the second one is of the format "dd.MM.yyyy".
     * </p>
     * 
     * @param dateOne the first date to be compared to the second
     * @param dateTwo the second date to be compared to the first
     * @return <code>true</code> if the dates are equal, otherwise <code>false</code>
     */
    public static boolean datesEqual(String dateOne, String dateTwo) {
        // cut off the leading weekday abbreviation
        String processedDateOne = dateOne.substring(4, 12);

        // split the String by its delimiter (/)
        String[] temp = processedDateOne.split("/");

        // concatenate the parts to fit the format of the second date
        String comparableDateOne = temp[0] + "." + temp[1] + ".20" + temp[2];

        // return the result of the String comparison
        return comparableDateOne.equals(dateTwo);
    }

    /**
     * Compares two dates and checks if they are equal using the comparison of {@link LocalDate}.
     * <p>
     * <strong>Important note:</strong><br>
     * This assumes the first date given is of the format "EEE, dd/MM/yy" and 
     * the second one is of the format "dd.MM.yyyy".
     * </p>
     * 
     * @param dateOne the first date to be compared to the second
     * @param dateTwo the second date to be compared to the first
     * @return <code>true</code> if the dates are equal, otherwise <code>false</code>
     */
    public static boolean equalDates(String dateOne, String dateTwo) {
        // define two formattings
        DateTimeFormatter firstFormatter = DateTimeFormatter.ofPattern("dd/MM/yy");
        DateTimeFormatter secondFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");

        // create two LocalDates, the first one still needs to have the weekday abbreviation cut off
        LocalDate firstDate = LocalDate.parse(dateOne.substring(4, 12), firstFormatter);
        LocalDate secondDate = LocalDate.parse(dateTwo, secondFormatter);

        // return the result of the LocalDate comparison
        return firstDate.equals(secondDate);
    }

    /**
     * The main method that just executes both possibilities 
     * of comparing differently formatted date {@link String}s
     * @param args (unused) command line arguments
     */
    public static void main(String[] args) {
        String dateOne = "Wed 01/08/18";
        String dateTwo = "01.08.2018";

        System.out.println("#### datesEqual ####");
        String datesEqual = datesEqual(dateOne, dateTwo) ?
                "The dates are equal" : "The dates differ";
        System.out.println(datesEqual);

        System.out.println("#### equalDates ####");
        String equalDates = equalDates(dateOne, dateTwo) ?
                "The dates are equal" : "The dates differ";
        System.out.println(equalDates);
    }
}

Please read all the comments in the code as they are the explanation of what the code does. 请阅读代码中的所有注释,因为它们是代码所做的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM