Sometime we need to generate CSV from data as per requirement. You can easily create CSV file by following the below steps:
- Write the following Maven configuration in pom.xml file in your project:
<dependency>
<groupid>net.sf.opencsv</groupid>
<artifactid>opencsv</artifactid>
<version>2.3</version>
</dependency>
- Now define the below method to create the CSV file:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
private void generateCsvFile(String fileName)
{
//Delimiter used in CSV file
private static final String COMMA_DELIMITER = ",";
private static final String NEW_LINE_SEPARATOR = "\n";
try {
FileWriter writer = new FileWriter(fileName);
//we need to write out the header line
writer.append("tickitId");
writer.append('COMMA_DELIMITER');
writer.append("subject");
writer.append('COMMA_DELIMITER');
writer.append("tickitType");
writer.append('NEW_LINE_SEPARATOR');
// write out a few records
writer.append("1");
writer.append('COMMA_DELIMITER');
writer.append("Test Tickit 1");
writer.append('COMMA_DELIMITER');
writer.append("assigned");
writer.append('NEW_LINE_SEPARATOR');
writer.append("2");
writer.append('COMMA_DELIMITER');
writer.append("Test Tickit 2");
writer.append('COMMA_DELIMITER');
writer.append("verified");
writer.append('NEW_LINE_SEPARATOR');
writer.append("3");
writer.append('COMMA_DELIMITER');
writer.append("Test Tickit 3");
writer.append('COMMA_DELIMITER');
writer.append("rejected");
writer.append('NEW_LINE_SEPARATOR');
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Output Format:
tickitId,subject,tickitType
1,Test Tickit 1,assigned
2,Test Tickit 2,verified
3,Test Tickit 3,rejected
Hope this will help you :)
0 Comment(s)