Creating a CSV File in java from a HashMap

前端 未结 2 1545
谎友^
谎友^ 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<string, ?="" super="" object=""> data1 = new HashMap<string, object="">();  
            data1.put(header[0], "Raj");  
            data1.put(header[1], "Vijayawada");  
            data1.put(header[2], 500026);  
            final HashMap<string, ?="" super="" object=""> data2 = new HashMap<string, object="">();  
            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

    0 讨论(0)
  • 2021-01-25 03:44

    If you really want an Excel file, the best library for creating one is Andy Khan's JExcel.

    I think you'd need one worksheet per flow, with .csv pairs for each one, sorted by time.

    If these are graphs of a variable versus time, wouldn't "time" be the first value in each pair?

    Here's how I'd do it. It works perfectly for the simple test case I supplied - it's working code that you'll be able to extend.

    package jexcel;
    
    import jxl.Workbook;
    import jxl.write.WritableSheet;
    import jxl.write.WritableWorkbook;
    import jxl.write.WriteException;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class JExcelUtils
    {
        public static void main(String[] args)
        {
            String fileName = ((args.length > 0) ? args[0] : "jexcel.xls");
            Map<String, List<Pair>> csv = new HashMap<String, List<Pair>>()
            {{
                put("Flow1", fromArrayToList(new double[][]
                {
                    { 0.0, 0.0 },
                    { 0.1, 1.0 },
                    { 0.2, 2.0 },
                    { 0.3, 3.0 },
                    { 0.4, 4.0 },
                    { 0.5, 5.0 },    
                }));
                put("Flow2", fromArrayToList(new double[][]
                {
                    { 0.0, 0.0 },
                    { 0.1, 1.0 },
                    { 0.2, 4.0 },
                    { 0.3, 9.0 },
                    { 0.4, 16.0 },
                    { 0.5, 25.0 },
                }));
            }};
            WritableWorkbook excelContents = null;
    
            try
            {
                File excelFile = new File(fileName);
                excelContents = createExcel(excelFile, csv);
                excelContents.write();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (WriteException e)
            {
                e.printStackTrace();
            }
            finally
            {
                try { if (excelContents != null) excelContents.close(); } catch (Exception e) { e.printStackTrace(); }
            }
        }
    
    
        public static List<Pair> fromArrayToList(double [][] input)
        {
            List<Pair> result = new ArrayList<Pair>();
    
            for (int i = 0; i < input.length; ++i)
            {
                result.add(new Pair(input[i][0], input[i][1]));            
            }
    
            return result;
        }
    
        public static WritableWorkbook createExcel(File excelFile, Map<String, List<Pair>> worksheets) throws IOException, WriteException
        {
            WritableWorkbook result = Workbook.createWorkbook(excelFile);
    
            int order = 0;
            for (String worksheetName : worksheets.keySet())
            {
                WritableSheet worksheet = result.createSheet(worksheetName, order++);
                List<Pair> worksheetValues = worksheets.get(worksheetName);
                for (int row = 0; row < worksheetValues.size(); ++row)
                {
                    worksheet.addCell(new jxl.write.Number(0, row, worksheetValues.get(row).getX()));
                    worksheet.addCell(new jxl.write.Number(1, row, worksheetValues.get(row).getY()));
                }
            }
    
            return result;
        }
    
    }
    
    
    class Pair
    {
        private double x;
        private double y;
    
        Pair(double x, double y)
        {
            this.x = x;
            this.y = y;
        }
    
        public double getX()
        {
            return x;
        }
    
        public double getY()
        {
            return y;
        }
    }
    
    0 讨论(0)
提交回复
热议问题