从 HashMap 在 java 中创建 CSV 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3487123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:02:17  来源:igfitidea点击:

Creating a CSV File in java from a HashMap

javaexcelcsvhashmap

提问by Red Lion

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.

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

What I need to do is, to draw graphs for each flow based on those values. for example:

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

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

i need to create a CSV file that then can be read from MS excel. Can anyone has the idea to give me some clues please?

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

Edited: here is my hashMap:

编辑:这是我的 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);


    }

回答by YoK

You can use from following API's.

您可以使用以下 API。

POI : http://poi.apache.org

兴趣点:http: //poi.apache.org

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

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

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

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

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

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

Following is writting to csv exampleusing supercsv api:

以下是使用 supercsv api写入 csv示例

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 :

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

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

您能否推荐一个用于读取(并可能写入)CSV 文件的 Java 库?

CSV API for Java

用于 Java 的 CSV API

回答by duffymo

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

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

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

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

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