用Java

时间:2016-12-06 00:34:25

标签: java excel csv

我需要以特定格式创建CSV文件。这是格式。

“ROWHEAD”,2016/09/13 03:24:42 -0700,”A”,”BCDE”,002,
“SECHEAD”,2016/09/12 00:00:00 -0700,2016/09/12 23:59:59 -0700,”BCDE”

“COLHEAD”,”Col A”,”Col B”,”Col C”,”Col D”,”Col E”,”Col F”
“SECBODY”,”val A”,”val B”,”val C”,”val D”,”val E”,”val F”
“SECBODY”,”val A”,”val B”,”val C”,”val D”,”val E”,”val F”
“SECBODY”,”val A”,”val B”,”val C”,”val D”,”val E”,”val F”
“SECBODY”,”val A”,”val B”,”val C”,”val D”,”val E”,”val F”

“SECFOOT”,”XXX”,0,0,0,0,”YY”,0,”ZZ”,0,189
“SECCOUNT”,1
"ROWFOOT”,”XXX”,0,0,0,0,”YY”,0,”ZZ”,0,189

我尝试过使用普通的文件编写器方法,这些方法无法帮助我实现这一目标。此外,我尝试使用openCSV API,甚至没有多大帮助。

如何创建一个包含相关页眉和页脚值的CSV文件?

1 个答案:

答案 0 :(得分:2)

获取uniVocity-parsers来处理此问题。它有OutputValueSwitch,它将匹配每行特定列中的值,以确定要使用的RowProcessor

例如,如果您的输入行是从java bean(它可能会这样做)生成的,而其他一些行是对象数组的简单列表:

    OutputValueSwitch writerSwitch = new OutputValueSwitch(0); //row identifiers go at column 0

    // If the value is "ROWHEAD", we want to use an BeanWriterProcessor. You can provide field names to be associated with the fields in the class.
    writerSwitch.addSwitchForValue("ROWHEAD", new BeanWriterProcessor(RowHead.class));

    writerSwitch.addSwitchForValue("SECHEAD", new BeanWriterProcessor(SecHead.class));

    // If the value is "SECBODY", a ObjectRowWriterProcessor will be used. Let's assume you are writing object arrays here
    writerSwitch.addSwitchForValue("SECBODY", new ObjectRowWriterProcessor()); 
    //...and so on.

    //Configure the CSV writer here
    CsvWriterSettings settings = new CsvWriterSettings();
    // the writer should use the switch defined above
    settings.setRowWriterProcessor(writerSwitch);

    settings.getFormat().setLineSeparator("\n");
    settings.setHeaderWritingEnabled(false);
    //etc

    //Create the CSV writer
    CsvWriter writer = new CsvWriter(new File("/path/to/your.csv"), "UTF-8", settings);

    writer.processRecord(new RowHead()); //writing bean
    writer.processRecord(new SecHead()); //writing the other bean
    writer.processRecord(new Object[]{"SECBODY", "Value 1", "Value 2", "etc"}); //writing an array

    writer.close();

您还可以使用地图作为输入行。有关完整的示例,请参阅thisthis

你可以对这个库做任何事情,我希望它可以帮到你。

披露:我是这个图书馆的作者。它是开源和免费的(Apache V2.0许可证)。