Merge CSV files into a single file with no repeated headers

后端 未结 5 1529
挽巷
挽巷 2020-12-30 10:39

I have some CSV files with the same column headers. For example

File A

header1,header2,header3
one,two,three
four,five,six

File B

5条回答
  •  孤独总比滥情好
    2020-12-30 10:53

    Late here but Fuzzy-Csv (https://github.com/kayr/fuzzy-csv/) was designed just for that.

    This is what the code would look like

            String csv1 = "NAME,SURNAME,AGE\n" +
                    "Fred,Krueger,Unknown";
    
            String csv2 = "NAME,MIDDLENAME,SURNAME,AGE\n" +
                    "Jason,Noname,Scarry,16";
    
            FuzzyCSVTable t1 = FuzzyCSVTable.parseCsv(csv1);
            FuzzyCSVTable t2 = FuzzyCSVTable.parseCsv(csv2);
    
            FuzzyCSVTable output = t1.mergeByColumn(t2);
    
            output.printTable();
    

    Output

    ╔═══════╤═════════╤═════════╤════════════╗
    ║ NAME  │ SURNAME │ AGE     │ MIDDLENAME ║
    ╠═══════╪═════════╪═════════╪════════════╣
    ║ Fred  │ Krueger │ Unknown │ -          ║
    ╟───────┼─────────┼─────────┼────────────╢
    ║ Jason │ Scarry  │ 16      │ Noname     ║
    ╚═══════╧═════════╧═════════╧════════════╝
    

    You can re-export your csv using one of the helper methods

    output.write("FilePath.csv");
    
    or 
    
    output.toCsvString()
    
    

提交回复
热议问题