We can't get directly records from db as csv file, there are many third-party libraries available for working with CSV files,
Let's take a look at a few of them:
- Open CSV: Another popular and actively-maintained CSV library
- Apache Commons CSV: Apache's CSV offering for working with CSV Files
- Flatpack: An open-source CSV library being actively developed
- CSVeed: Open-source and actively-maintained.
Sample code for open csv, add your open csv jar to you class path.
create one csv file and add its location to the code below
File file = new File(filePath);
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(file);
// create CSVWriter object filewriter object as parameter
CSVWriter writer = new CSVWriter(outputfile);
// adding header to csv
String[] header = { "id", "name", "design" };
writer.writeNext(header);
// add data to csv
// in loop
String[] data = {}
writer.writeNext(data);
// execute this two line until your data remains.
// closing writer connection
writer.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
After creating the file set content type as csv and flush the buffer the browser will download the file for end user.
resp.setContentType("application/csv");
resp.setHeader(HttpHeaders.CONTENT_DISPOSITION, file);
inStrm = new FileInputStream(file);
FileCopyUtils.copy(inStrm, resp.getOutputStream());
resp.flushBuffer();