Since JavaScript itself does not have permission to operate local files, unless you use ActiveX, this is cumbersome and unsafe, and I don’t want to use it at all. Therefore, the method of obtaining data from the table on the page and saving it into a local file will not work.
What we want to export is the data in the table, and the data in the table comes from the server, so we can just download the data on the server to the local and save it as a file.
Server-side implementation code:
ServletOutputStream out = null;
try{
//Set the header information of the output csv
response.setContentType("text/csv");
String disposition = "attachment; fileName=data.csv";
response.setHeader("Content-Disposition ", disposition);
//Get the output object
out = response.getOutputStream();
//Get the data
byte[] blobData = CSVParser.parseCsv(rs).getBytes();
out.write(blobData);
out.flush();
out.close();
}catch(Exception e){
throw e;
}finally{
if(out != null)
out.close();
}
There is a code that needs to be explained CSVParser.parseCsv(rs). CSVParser is what I am doing A class implemented elsewhere that converts ResultSet objects retrieved from the database into CSV data. The parameter rs of the parseCsv method is the ResultSet object. What is returned is string data in csv format
I downloaded the client using iframe. I wrote a more general method. You can put this function in a js file and call it directly on the page when using it
//Bring in the url according to the query data Return csv
function bsuExportCsv(url){
//If there is no iframe for downloading on the page, add iframe to the page
if($('#downloadcsv').length<=0)
$('body').append("");
$('#downloadcsv').attr(' src',url);
}
url is the address of the servlet that requests data. This address must return data in csv format
First determine whether there is an iframe with the id downloadcsv in the page. If there is no iframe in the body tag, then set the src attribute of the iframe to the incoming url address.
When using it, you just need to call bsuExportCsv("http://localhost:8080/csvservelt") on the page you want to export.