Creating a CSV File in java from a HashMap

前端 未结 2 1546
谎友^
谎友^ 2021-01-25 02:54

I have a hashMap in java in terms of some keys which each key is indicating a flow. Then each value showing statics about each packet belongs to that flow.

What I need t

2条回答
  •  生来不讨喜
    2021-01-25 03:34

    You can use from following API's.

    POI : http://poi.apache.org

    javacsv : http://sourceforge.net/projects/javacsv

    JExcel : http://jexcelapi.sourceforge.net/

    opencsv : http://opencsv.sourceforge.net/

    Following is writting to csv example using supercsv api:

    import java.io.FileWriter;
    import java.util.HashMap;
    import org.supercsv.io.*;
    import org.supercsv.prefs.CsvPreference;
    
    public class CSVWriteExample {
    
        /**
         * @param args
         */
        public static void main(String[] args) throws Exception{  
    
          ICsvMapWriter writer = new CsvMapWriter(new FileWriter("person.csv"), CsvPreference.EXCEL_PREFERENCE);  
          try {  
            final String[] header = new String[] { "name", "city", "pin" };  
            // set up some data to write  
            final HashMap data1 = new HashMap();  
            data1.put(header[0], "Raj");  
            data1.put(header[1], "Vijayawada");  
            data1.put(header[2], 500026);  
            final HashMap data2 = new HashMap();  
            data2.put(header[0], "Suneel");  
            data2.put(header[1], "Tenali");  
            data2.put(header[2], 522202);  
    
            // the actual writing  
            writer.writeHeader(header);  
            writer.write(data1, header);  
            writer.write(data2, header);  
    
            System.out.println("Writing Completed...!");  
          } finally {  
            writer.close();  
          }  
     }
    }
    

    Also realted questions on stackoverflow can be found :

    Can you recommend a Java library for reading (and possibly writing) CSV files?

    CSV API for Java

提交回复
热议问题