Reputation: 16430
I need to create a CSV file in a specific format. Here is the format.
“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
I have tried using the normal file writer ways which couldn't help me achieving this. Also I tried openCSV API for the same which even doesn't help much.
How can I create a CSV file with such header and footer values associated in it?
Upvotes: 0
Views: 458
Reputation: 6289
Get uniVocity-parsers to handle this. It has an OutputValueSwitch
which will match a value in a particular column of each row to determine a RowProcessor
to use.
For example, if your input rows are generated from java beans (which it probably does), and some other rows are plain lists of object arrays:
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();
You can also use maps as input rows. For fully working examples, refer to this and this
You can do anything with this library and I hope it helps you.
Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).
Upvotes: 2