7.3 Building Excel Spreadsheets

Although servlets usually generate HTML output, they are not required to do so. HTTP is fundamental to servlets; HTML is not. Now, it is sometimes useful to generate Microsoft Excel content so that users can save the results in a report and so that you can make use of the built-in formula support in Excel. Excel accepts input in at least three distinct formats: tab-separated data, HTML tables, and a native binary format.

In this section, we illustrate the use of tab-separated data to generate spreadsheets. In Chapter 12 (Controlling the Structure of Generated Servlets: The JSP page Directive), we show how to build Excel spreadsheets by using HTML-table format. No matter the format, the key is to use the Content-Type response header to tell the client that you are sending a spreadsheet. You use the shorthand setContentType method to set the Content-Type header, and the MIME type for Excel spreadsheets is application/vnd.ms-excel . So, to generate Excel spreadsheets, just do:

 response.setContentType("application/vnd.ms-excel"); PrintWriter out = response.getWriter(); 

Then, simply print some entries with tabs ( \t in Java strings) in between. That's it: no DOCTYPE , no HEAD , no BODY : those are all HTML-specific things.

Listing 7.1 presents a simple servlet that builds an Excel spreadsheet that compares apples and oranges. Note that =SUM( col:col ) sums a range of columns in Excel. Figure 7-1 shows the results.

Listing 7.1 ApplesAndOranges.java
 package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** Servlet that creates Excel spreadsheet comparing  *  apples and oranges.  */ public class ApplesAndOranges extends HttpServlet {   public void doGet(HttpServletRequest request,                     HttpServletResponse response)       throws ServletException, IOException {  response.setContentType("application/vnd.ms-excel");  PrintWriter out = response.getWriter();       out.println("\tQ1\tQ2\tQ3\tQ4\tTotal");       out.println("Apples\t78\t87\t92\t29\t=SUM(B2:E2)");       out.println("Oranges\t77\t86\t93\t30\t=SUM(B3:E3)");   } } 
Figure 7-1. Result of the ApplesAndOranges servlet in Internet Explorer on a system that has Microsoft Office installed.


Core Servlets and JavaServer Pages (Vol. 1.Core Technologies)
Core Servlets and Javaserver Pages: Core Technologies, Vol. 1 (2nd Edition)
ISBN: 0130092290
EAN: 2147483647
Year: 2002
Pages: 194

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net