Java learning path: Export and download of Java Excel operations, javaexcel
Place a button on the page to click Export event
<H: commandLink target = "_ parent" value = "Export"
Action = "# {eveluatesubject. doSaveExcel }"
StyleClass = "cssButtonBG">
</H: commandLink>
Background export Method
/**
* Export an EXCEL file
*
* @ Param request
* @ Return
*/
Public String doSaveExcel (){
HttpServletRequest request = (HttpServletRequest) FacesContext
. GetCurrentInstance (). getExternalContext (). getRequest ();
Dooutof (request );
Return null;
}
Public String dooutof (HttpServletRequest request ){
// File name and Path
String realPath = request. getRealPath ("");
String fileName = "exported file name .xls ";
File file = new File (realPath + "// xxfzpj // tempPath //"); // location where the exported File is stored
If (! File. exists ()){
File. mkdirs ();
}
RealPath = realPath + "// xxfzpj // tempPath //" + fileName;
// Create a working thin table and write the header
Try {
WritableWorkbook wwb = Workbook. createWorkbook (new File (realPath ));
WritableSheet ws = wwb. createSheet ("Sheet1", 0); // create a workbook
// Write the table Header
Jxl. write. Label label1 = new jxl. write. Label (0, 0, "column 1 ");
Jxl. write. Label label2 = new jxl. write. Label (1, 0, "column 2 ");
Jxl. write. Label label3 = new jxl. write. Label (2, 0, "column 3 ");
Jxl. write. Label label4 = new jxl. write. Label (3, 0, "column 4 ");
Jxl. write. Label label5 = new jxl. write. Label (4, 0, "column 5 ");
Ws. addCell (label1); // Add it to the workbook
Ws. addCell (label2 );
Ws. addCell (label3 );
Ws. addCell (label4 );
Ws. addCell (label5 );
// Write information
List <Map> listmsg = content read from the database (Execute SQL );
For (int I = 0; I <listmsg. size (); I ++ ){
Label1 = new jxl. write. Label (0, I + 1, listmsg. get (I). get (
"Subject_id"). toString (). trim (); // create the first column
Label2 = new jxl. write. Label (1, I + 1, listmsg. get (I). get (
"Subject_name"). toString (). trim (); // create the second column
If (listmsg. get (I). get ("object_name ")! = Null
&&""! = Listmsg. get (I). get ("object_name ")){
Label3 = new jxl. write. Label (2, I + 1, listmsg. get (I). get (
"Object_name"). toString (). trim (); // create the third column
} Else {
Label3 = new jxl. write. Label (2, I + 1, "No rating Object Name Defined! ");
}
Label4 = new jxl. write. Label (3, I + 1, listmsg. get (I). get (
"Mode_name"). toString (). trim (); // create the fourth column
Label5 = new jxl. write. Label (4, I + 1, listmsg. get (I). get (
"Type_name"). toString (). trim (); // create the Fifth Column
Ws. addCell (label1); // Add it to the workbook
Ws. addCell (label2 );
Ws. addCell (label3 );
Ws. addCell (label4 );
Ws. addCell (label5 );
}
// Write the Exel Worksheet
Wwb. write ();
// Close the Excel worksheet object
Wwb. close ();
// Download
FacesContext ctx = FacesContext. getCurrentInstance ();
String contentType = "application/x-download ";
HttpServletResponse response = (HttpServletResponse) ctx
. GetExternalContext (). getResponse ();
Response. setContentType (contentType );
Response. setHeader ("Content-Disposition", "attachment; filename ="
+ New String (fileName. getBytes ("gb2312"), "ISO8859-1 "));
HttpServletRequest request1 = (HttpServletRequest) FacesContext
. GetCurrentInstance (). getExternalContext (). getRequest ();
ServletOutputStream out = response. getOutputStream ();
Byte [] bytes = new byte [0 xffff];
InputStream is = new FileInputStream (new File (realPath ));
Int B = 0;
While (B = is. read (bytes, 0, 0 xffff)> 0 ){
Out. write (bytes, 0, B );
}
Is. close ();
Out. flush ();
Ctx. responseComplete ();
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} // Create a path here
Return null;
}
How does java download exported excel files to the client?
Package com. mr; import java. io. IOException; import java. io. printWriter; import javax. servlet. servletException; import javax. servlet. servletOutputStream; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse;/*** use Servlet to export Excel * @ author CHUNBIN **/public class ExportExcelServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost (request, response);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); // sets the request encoding method to prevent Chinese garbled String fileName = "export data "; // set the exported file name StringBuffer sb = new StringBuffer (request. getParameter ("tableInfo"); // puts the table information into the memory String contentType = "application/vnd. ms-excel "; // defines the String recommendedName = new String (fileName. getBytes (), "iso_8859_1"); // sets the file name encoding format response. setContentType (contentType); // set the export file format response. setHeader ("Content-Disposition", "attachment; filename =" + recommendedName + "\" "); // response. resetBuffer (); // use output to input ...... remaining full text>
Export java excel to a local user
In general, the download function is indeed directed to a temporary directory on the server, and then read the excel file with a piece of code and output it to the response stream, give you a piece of usable code
// ------------------------------ // Step1. save a temporary excel file to the temp directory. // ------------------------------ // You can implement this part by yourself, I believe you have implemented // suppose you have saved an excel File to a Temporary Folder. // a File has been generated pointing to this temporary excel File, the name is exportFile // --------------------------- // step2. the Download Dialog Box // ----------------------------------- if (exportFile = null) {logger. error ("excel generation error! ExportFile is blank "); return;} // create a file read stream to read this temporary excel file FileInputStream fs = null; try {fs = new FileInputStream (exportFile );} catch (FileNotFoundException e) {logger. error ("excel generation error! "+ ExportFile +" does not exist! ", E); return;} // set the response header and save the file name HttpServletResponse response = ServletActionContext. getResponse (); // This must be set to tell the browser that this request is a downloaded data stream response. setContentType ("APPLICATION/OCTET-STREAM"); try {// here, replace the "purchasing department's monthly purchase report. xls" with the file name excelName = URLEncoder you want to display to the user. encode ("purchasing department monthly purchase report .xls", "UTF-8");} catch (UnsupportedEncodingException e1) {logger. error ("An error occurred while converting the excel name encoding! ", E1);} response. setHeader ("Content-Disposition", "attachment; filename = \" "+ excelName +" \ ""); // write stream information int B = 0; try {...... remaining full text>