Use spring MVC to generate EXCEL and PDF files

Source: Internet
Author: User

HTML pages are not always the best way to display data output to users. Spring supports dynamic generation of PDF or Excel files from data and makes this process easy. The document itself is a view. When the Server adds the content type to return the document as a stream, the client PC only needs to run the spreadsheet software or PDF browsing software. The following is a simple example: two buttons on the interface, one for Excel
To use an Excel worksheet, you need to add the 'poi' library file to your classpath. For a PDF file, you need the itext. jar file. They are all included in the main release package of spring. In addition to the test also need to add package spring-beans.jar, spring-context.jar, spring-web.jar, spring-webmvc.jar.

1. The web. xml configuration file is mainly used to configure the corresponding servlet.
<! --
Spring MVC servlet, which will load the WEB-INF/spring-servlet.xml to start spring
MVC module -->
<Servlet>
<Servlet-Name> springmvc </servlet-Name>
<Servlet-class> org. springframework. Web. servlet. dispatcherservlet </servlet-class>
<Load-on-startup> 1 </load-on-startup>
</Servlet>
<Servlet-mapping>
<Servlet-Name> springmvc </servlet-Name>
<URL-pattern> *. Form </url-pattern>
</Servlet-mapping>

2. Control File and spring-servlet.xml configuration, add viewcontroller Configuration
<! --
Generate an Excel or PDF view -->
<Bean
Class = "com. lzk. Controller. viewcontroller">
</Bean>

3. viewcontroller code
Package
Com. lzk. Controller;

Import java. util. arraylist;
Import
Java. util. hashmap;
Import java. util. List;
Import java. util. Map;
Import
Javax. servlet. http. httpservletrequest;
Import
Javax. servlet. http. httpservletresponse;
Import
Org. springframework. stereotype. Controller;
Import
Org. springframework. Web. Bind. annotation. requestmapping;
Import
Org. springframework. Web. Bind. annotation. requestmethod;
Import
Org. springframework. Web. servlet. modelandview;
Import
Com. SUPCON. Electronic. Its. Common. viewexcel;
Import
Com. SUPCON. Electronic. Its. Common. viewpdf;
/**
* An attempt to generate an Excel or PDF type
*
Assemble data based on parameters and jump to the corresponding view page
* View Controller bean <br>
*
* @ Author
Tony Lin created on 2008-10-22
* @ Version Version
1.0
*/

@ Controller
@ Requestmapping ("/view. Form ")
Public class
Viewcontroller extends basecontroller
{

@ Requestmapping (Params = "method = exceltest", method = requestmethod. Get)
Public
Modelandview viewexcel (httpservletrequest request, httpservletresponse
Response ){
Log. debug ("viewcontroller. viewexcel is
Started ......");
List list = new arraylist ();
Map model = new
Hashmap ();
List. Add ("test1 ");
List. Add ("Test2 ");

Model. Put ("list", list );
Viewexcel = new
Viewexcel ();
Log. debug ("viewcontroller. viewexcel is
Ended ......");
Return new modelandview (viewexcel, model );

}

@ Requestmapping (Params = "method = test", method = requestmethod. Get)
Public
Modelandview viewpdf (httpservletrequest request,

Httpservletresponse response) throws exception {

List list = new arraylist ();
Map model = new
Hashmap ();
List. Add ("test1 ");
List. Add ("Test2 ");

Model. Put ("list", list );
Viewpdf = new
Viewpdf ();
Return new modelandview (viewpdf, model );
}

}

4. View subclass for Excel View
Package com. lzk. Common;
Import
Java. util. date;
Import java. util. Map;
Import
Javax. servlet. http. httpservletrequest;
Import
Javax. servlet. http. httpservletresponse;
Import
Org. Apache. Poi. hssf. usermodel. hssfcell;
Import
Org. Apache. Poi. hssf. usermodel. hssfcellstyle;
Import
Org. Apache. Poi. hssf. usermodel. hssfdataformat;
Import
Org. Apache. Poi. hssf. usermodel. hssfrow;
Import
Org. Apache. Poi. hssf. usermodel. hssfsheet;
Import
Org. Apache. Poi. hssf. usermodel. hssfworkbook;
Import
Org.springframework.web.servlet.view.doc ument. abstractexcelview;
/**
*
Generate an Excel view, which can be opened or saved using an Excel Tool
* Returned new by viewcontroller
Modelandview (viewexcel, model) generation
* @ Author Tony Lin created on
2008-10-22
* @ Version Version 1.0
*/
Public class viewexcel extends
Abstractexcelview {

Public void buildexceldocument (MAP model,
Hssfworkbook workbook,
Httpservletrequest request,
Httpservletresponse response)
Throws exception {


Hssfsheet sheet = Workbook. createsheet ("list ");

Sheet. setdefacolumcolumnwidth (short) 12 );


Hssfcell cell = getcell (sheet, 0, 0 );

Settext (cell, "Spring Excel test ");


Hssfcellstyle datestyle = Workbook. createcellstyle ();

// Datestyle. setdataformat (hssfdataformat. getbuiltinformat ("mm/DD/YYYY "));

Cell = getcell (sheet, 1, 0 );

Cell. setcellvalue ("Date: 2008-10-23 ");

// Cell. setcellstyle (datestyle );
Getcell (sheet, 2,
0). setcellvalue ("Test 1 ");
Getcell (sheet, 2, 1). setcellvalue ("Test 2 ");


Hssfrow sheetrow = sheet. createrow (3 );
For
(Short I = 0; I <10; I ++ ){

Sheetrow. createcell (I). setcellvalue (I * 10 );
}


}
}

5. View subclass for PDF view
Package lzk. Common;
Import
Java. util. List;
Import java. util. Map;
Import
Javax. servlet. http. httpservletrequest;
Import
Javax. servlet. http. httpservletresponse;
Import
Org.springframework.web.servlet.view.doc ument. abstractintoview;
Import
Com. lowagie. Text. Document;
Import com. lowagie. Text. Paragraph;
Import
Com.lowagie.text.html. writable writer;
/**
* Generate a PDF view, which can be opened or saved in the ghost browser.
*
Generated by return New modelandview (viewpdf, model) of viewcontroller
* @ Author Tony Lin
Created on 2008-10-22
* @ Version Version 1.0
*/
Public class viewpdf
Extends abstractintoview {
Public void build1_document (MAP model,
Document document,
Pdfwriter writer, httpservletrequest
Request,
Httpservletresponse response) throws exception {


List list = (list) model. Get ("list ");

For
(INT I = 0; I <list. Size (); I ++)
Document. Add (New
Paragraph (string) list. Get (I )));
}
}

6. jsp page call
<
Href = "<% = PATH %>/view. Form? Method = release test"
Target = "blank"> Save the PDF file </a>
<Input name = "button" type = "button"
Id = "button" value = "Save excel"
Onclick = "javascript: window. Open ('<% = path
%>/View. Form? Method = exceltest'); "/>

The above code is based on spring2.5, jdk1.5, and tomcat1.5.

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.