Export excel in SHH (using POI)

Source: Internet
Author: User

1. In struts. xml

<Action name = "exportexcelaction" class = "com. Ht. Action. Exam. examresultaction"> <result name = "success" type = "stream"> <! -- Type = "stream" indicates the binary file to be downloaded --> <Param name = "contenttype"> application/vnd. MS-Excel </param> <! -- Specify the file type --> <Param name = "contentdisposition"> attachment; filename = "grade_analysis.xls" </param> <! -- The attachment attribute is to be opened separately, rather than in the browser. The default value is inline. specify the name of the downloaded file --> <Param name = "inputname"> exportresult </param> <! -- Specifies the name of the method for downloading an object. Here, special attention must be given to the same method name as the method name in action --> </result> </Action>

 

 

2. In the action

Public inputstream getexportresult () throws unsupportedencodingexception {// The get method name must be consistent with struts. claid = java.net. urldecoder. decode (claid, "UTF-8"); // decode STR = java.net in order to solve the garbled problem of JS value passing. urldecoder. decode (STR, "UTF-8"); return this. resultservice. getinputstream (claid, STR );}

 

 

3. In Service

// Export the public inputstream getinputstream (string claid, string Str) in Excel; // This is a method for defining the input stream

 

 

4. At the service Implementation Layer

/** Process Excel export **/Public inputstream getinputstream (string claid, string Str) {// system. out. println ("class" + claid + "string" + Str); // process the passed string [] type = Str. split ("-"); int Len = type. length; // system. out. println ("array length:" + Len); hssfworkbook WB = new hssfworkbook (); // use poi to import a POI package, first, generate an hssfworkbook object hssfsheet sheet = WB. createsheet ("sheet1"); // create an Excel sheet. createrow (0); // create the first hssfcell cell = row. createcell (short) 0); // create the first cell. setencoding (hssfcell. encoding_utf_16); // set the encoding format for each cell. setcellvalue ("Serial Number"); For (INT I = 0; I <Len; I ++) {Cell = row. createcell (short) (I + 1); // create cells in sequence. setencoding (hssfcell. encoding_utf_16); // set the encoding format for each cell. setcellvalue (type [I]);}/* the header has been designed. ** The following is the data read from the database */string querystring = "from result as res where res. student. classes. claid = "+ claid; List <result> res = NULL; Res = resultdao. getlistbyhql (querystring); // store the expected score records to the for (INT I = 0; I <res. size (); I ++) {result = res. get (I); // get a record ROW = sheet. createrow (I + 1); // generate the following cell = row. createcell (short) 0); // the first cell. setencoding (hssfcell. encoding_utf_16); cell. setcellvalue (I + 1); For (int A = 0; A <Len; A ++) {// The following cells are displayed in sequence. // system. out. println ("who is now" + type [a]); cell = row. createcell (short) (a + 1); cell. setencoding (hssfcell. encoding_utf_16); If (type [A]. equals ("student ID") {Cell. setcellvalue (result. getstudent (). getstunum ();} else if (type [A]. equals ("examinee name") {Cell. setcellvalue (result. getstudent (). getstuname ();} else if (type [A]. equals ("examinee name") {Cell. setcellvalue (result. getstudent (). getstuname ();} else if (type [A]. equals ("examinee class") {Cell. setcellvalue (result. getstudent (). getclasses (). getclaname ();} else if (type [A]. equals ("gender") {Cell. setcellvalue (result. getstudent (). getstusex ();} else if (type [A]. equals ("Exam Score") {Cell. setcellvalue (result. getresscore ();} else if (type [A]. equals ("test time") {Cell. setcellvalue (result. getresbegin ();} else if (type [A]. equals ("Submit time") {Cell. setcellvalue (result. getresend ();} else if (type [A]. equals ("Exam time") {try {Cell. setcellvalue (gettimedifference (result. getresend (), result. getresbegin ();} catch (exception e) {e. printstacktrace () ;}}}/ ** the required Excel file is generated. * write another method to avoid temporary files, in the memory */bytearrayoutputstream OS = new bytearrayoutputstream (); try {WB. write (OS);} catch (ioexception e) {e. printstacktrace ();} byte [] content = OS. tobytearray (); inputstream is = new bytearrayinputstream (content); return is ;}

 

 

5. resultdao

  

public List<Result> getListByHQL(String queryString);

 

 

6. DAO implementation Layer

public List<Result> getListByHQL(String queryString){     return getHibernateTemplate().find(queryString); }

 

 

7. resullt object class

  

package com.ht.entity;/**  * Result entity. @author MyEclipse Persistence Tools */public class Result implements java.io.Serializable { // Fields private Integer resId;  private Student student;  private ClassTest classTest;  private String resBegin;  private String resEnd;  private String resScore; // Constructors /** default constructor */  public Result() {  } /** full constructor */  public Result(Student student, ClassTest classTest, String resBegin,    String resEnd, String resScore){    this.student = student;     this.classTest = classTest;      this.resBegin = resBegin;      this.resEnd = resEnd;     this.resScore = resScore;  } // Property accessors public Integer getResId() {   return this.resId;  } public void setResId(Integer resId) {   this.resId = resId;  } public Student getStudent() {   return this.student;  } public void setStudent(Student student) {   this.student = student;  } public ClassTest getClassTest() {   return this.classTest;  } public void setClassTest(ClassTest classTest) {   this.classTest = classTest;  } public String getResBegin() {   return this.resBegin;  } public void setResBegin(String resBegin) {   this.resBegin = resBegin;  } public String getResEnd() {   return this.resEnd;  } public void setResEnd(String resEnd) {   this.resEnd = resEnd;  } public String getResScore() {   return this.resScore;  } public void setResScore(String resScore) {   this.resScore = resScore;  }}

 

 

 

 

8. Presentation Layer

<HTML> 

 

 

6. JS is also used for passing values, which can be modified as needed.

JS:

// Export an Excel file. You cannot use Ajax function exportexcel (tagaction) {var claid = $ ("# claid "). val (); var input = $ ("input [name = 'std']"); // obtain all values first, and Judge var STR = "" Through loops ""; for (I = 0; I <input. length; I ++) {If (input [I]. checked) {STR = STR + input [I]. value + "-"; // connect the selected item to the background as a string} If (claid = "0") {alert ("select a class first! "); Return;} If (STR = NULL | STR =") {alert ("select the item to export first! "); Return;} // garbled, two encodeuri packages window. Location. href =" exportexcelaction. Action? Claid = "+ encodeuri (claid) +" & STR = "+ encodeuri (STR) + "";}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.