Datasheet

Patrick c01.tex V3 - 09/18/2009 12:15pm Page 27
Chapter 1: Building Web Applications in WebLogic
To create a spreadsheet using a servlet, build the servlet in the normal manner but set the content type to
application/vnd.ms-excel
in the response header to indicate that the response should be interpreted
as a spreadsheet. Data written to the response
Writer
object will be interpreted as spreadsheet data,
with tabs indicating column divisions and newline characters indicating row divisions. For example, the
SimpleExcelServlet
servlet in Listing 1-4 creates a multiplication table using simple tabs and newlines
to control the rows and columns in the result.
Listing 1-4: SimpleExcelServlet.java.
package professional.weblogic.ch01.example2;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleExcelServlet extends HttpServlet
{
public static final String CONTENT_TYPE_EXCEL =
"application/vnd.ms-excel";
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException
{
PrintWriter out = response.getWriter();
response.setContentType(CONTENT_TYPE_EXCEL);
out.print("\t"); // empty cell in upper corner
for (int jj = 1; jj <= 10; jj++) {
out.print("" + jj + "\t");
}
out.print("\n");
for (int ii = 1; ii <= 10; ii++) {
out.print("" + ii + "\t");
for (int jj = 1; jj <= 10; jj++) {
out.print("" + (ii * jj) + "\t");
}
out.print("\n");
}
}
}
Normal registration of this servlet in
web.xml
is all that is required in most cases.
<servlet>
<servlet-name>SimpleExcelServlet</servlet-name>
<servlet-class>
professional.weblogic.ch01.example2.SimpleExcelServlet
</servlet-class>
</servlet>
<servlet-mapping>
27