Write a javaBean file and use JExcelApi to dynamically generate an excel file. Here I will write a simple and schematic file. Complex, you may need to query the database or something.
- package com.jagie.test
- import java.io.
- import jxl.
- import jxl.write.
- import jxl.format.
- import java.util.
- import java.awt.Color
- public class Test
Write a JSP file to use the Test javabean to output the excel file.
- <%@page import="com.jagie.test.Test" %>
- <%
- response.reset();
- response.setContentType("application/vnd.ms-excel");
- Test.writeExcel(response.getOutputStream());
- %>
In this way, you can use ie to access test_excel.JSP to open the dynamically generated excel file in ie. No garbled characters.
Someone may ask: response. reset (); can you leave this sentence alone? I suggest writing it unless you can ensure that there is nothing in the buffer of response.
Someone may ask: I add <% @ page contentType = "application/vnd. ms-excel; charset = GBK "%> to remove response. setContentType ("application/vnd. ms-excel "); OK? To answer this question, it is easy to check the java code generated after JSP is compiled by the JSP server. If so, the schematic code of the java file generated after my welogic7 compiles test_excel.JSP is as follows:
- public void _jspService(javax.servlet.http.HttpServletRequest
request,
- javax.servlet.http.HttpServletResponse response) throws
java.io.IOException,
- javax.servlet.ServletException catch (Throwable __ee)
-
-
- //before final close brace...
- }
Obviously, blocking response. setContentType ("application/vnd. ms-excel "); then, in the Test. writeExcel (response. getOutputStream (); before, response. the correct type of response contenttype is not set after reset (); of course, the output is garbled. The compiled source code of the JSP correct output of excel is as follows:
- public void _jspService(javax.servlet.http.HttpServletRequest request,
- javax.servlet.http.HttpServletResponse response) throws
java.io.IOException,
- javax.servlet.ServletException
- catch (Throwable __ee)
-
-
- //before final close brace...
- }
You can see that the output content of response is set correctly before Test. writeExcel (response. getOutputStream (); after response. reset. So the output is normal.
- JSP custom tags are explained in detail from the beginning to the end.
- How to configure and use fckeditor in JSP Environment
- Storage and display of images in databases Based on JSP
- Methods for constructing JSP and Javabean development and release Environments
- Examples of JSP + JavaBean + Servlet Working Principles