Recently, we need to implement the excel file export function on the web page. The following describes the specific implementation methods and ideas. Because javascript itself has no permission to operate on local files, unless ActiveX is used, however, this is troublesome and insecure. therefore, it is impossible to obtain the local file for saving data from the table on the page.
What we want to export is the data in the table, and the data in the table is from the server, so we can save the data on the server to a local file.
Server implementation code:
The Code is as follows:
ServletOutputStream out = null;
Try {
// Set the output csv Header
Response. setContentType ("text/csv ");
String disposition = "attachment; fileName=data.csv ";
Response. setHeader ("Content-Disposition", disposition );
// Obtain the output object
Out = response. getOutputStream ();
// Obtain 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 ();
}
It is necessary to explain the code in CSVParser. parseCsv (rs ). CSVParser is a class that I implement elsewhere to convert the ResultSet object found in the database to CSV data. the rs parameter of the parseCsv method is the ResultSet object. returns string data in csv format.
I used iframe to download the client. I wrote a general method. You can put this function in a js file and call it directly on the page.
The Code is as follows:
// The csv file is returned Based on the queried data.
Function bsuExportCsv (url ){
// If the iframe is not downloaded on the page, add the iframe to the page.
If ($ ('# downloadcsv'). length <= 0)
$ ('Body'). append ("");
$ ('# Downloadcsv'). attr ('src', url );
}
The url is the servlet address to request data. The url must be in csv format.
First, determine whether there is an iframe with the id of downloadcsv in the page. If the iframe is not added to the body tag, then set the src attribute of iframe to the passed url address.
You can call bsuExportCsv ("http: // localhost: 8080/csvservelt") on the page to export data.