Below is the well tested code to generate CSV using JAVA
Note: Need to download javacsv2.1.zip file for the same
<%@ page import="com.csvreader.CsvWriter" %>
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, false), ',');
String outputFile=getServletContext().getRealPath("/")+"/CSVFOLDER/OPCSV.CSV";
// before we open the file check to see if it already exists
boolean alreadyExists = new File(outputFile).exists();
// If the file didn't already exist then we need to write out the header line
if (!alreadyExists)
{
csvOutput.write("NAME");
csvOutput.write("EMPID");
csvOutput.endRecord();
}
csvOutput.write(request.getParameter("name"));
csvOutput.write(request.getParameter("empid"));
csvOutput.endRecord();
csvOutput.close();
In some systems the csv file will be opened directly in the browser instead of giving option to open/save.
In that case we need to use "type" attribute in the anchor tag.
Below is the example for the same.
<a href='/IOBCSV/IOBNEFTBULK"+iobseq+".CSV' type='application/csv' target='_blank'><b>Download CSV file </b></a>
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, false), ',');
String outputFile=getServletContext().getRealPath("/")+"/CSVFOLDER/OPCSV.CSV";
// before we open the file check to see if it already exists
boolean alreadyExists = new File(outputFile).exists();
// If the file didn't already exist then we need to write out the header line
if (!alreadyExists)
{
csvOutput.write("NAME");
csvOutput.write("EMPID");
csvOutput.endRecord();
}
csvOutput.write(request.getParameter("name"));
csvOutput.write(request.getParameter("empid"));
csvOutput.endRecord();
csvOutput.close();
In some systems the csv file will be opened directly in the browser instead of giving option to open/save.
In that case we need to use "type" attribute in the anchor tag.
Below is the example for the same.
<a href='/IOBCSV/IOBNEFTBULK"+iobseq+".CSV' type='application/csv' target='_blank'><b>Download CSV file </b></a>
No comments:
Post a Comment