从HashMap在java中创建CSV文件

时间:2010-08-15 11:15:27

标签: java excel csv hashmap

我在java中有一些hashMap,每个键都指示一个流。然后,显示每个数据包的静态的每个值都属于该流。

我需要做的是,根据这些值为每个流绘制图形。例如:

  Flow1: {[length, time],[],[],...}
  Flow2: {[length, time],[length, time],[],...}

我需要创建一个CSV文件,然后可以从MS excel中读取。任何人都有想法给我一些线索吗?

编辑: 这是我的hashMap:

    Iterator<Flows> iterator =  myHashMap.keySet().iterator();
    String fileName = ((args.length > 0) ? args[0] : "jexcel.xls");
    Map<String, ArrayList> csv = new HashMap<String, ArrayList>();
    int i=0;

    while(iterator.hasNext()){
        Flows key = iterator.next();
        ArrayList value = myHashMap.get(key);
        csv.put("Flow["+i+"]", value);


    }

2 个答案:

答案 0 :(得分:2)

您可以使用以下API。

POI:http://poi.apache.org

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

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

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

以下是使用supercsv api写入csv example

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();  
      }  
 }
}

还可以找到有关stackoverflow的问题:

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

CSV API for Java

答案 1 :(得分:2)

如果您真的想要一个Excel文件,那么用于创建Excel文件的最佳库是Andy Khan's JExcel

我认为每个流程需要一个工作表,每个流程都有.csv对,按时间排序。

如果这些是变量与时间的关系图,那么“时间”不是每对中的第一个值吗?

我是这样做的。它适用于我提供的简单测试用例 - 它是您能够扩展的工作代码。

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;
    }
}