用Java创buildCSV文件

我需要创build一个特定格式的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的相同甚至没有什么帮助。

我怎样才能创build一个CSV文件与这样的页眉和页脚值相关联?

获取uniVocityparsing器来处理这个问题。 它有一个OutputValueSwitch ,它将匹配每行的特定列中的一个值,以确定要使用的RowProcessor

例如,如果你的input行是从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(); 

您也可以使用地图作为input行。 完整的例子,参考这个和这个

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

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