posts - 9, comments - 1, trackbacks - 0, articles - 0

Servlet 利用jxl访问excel

Posted on 2009-12-06 17:42 TonyZhangtl 阅读(894) 评论(1)  编辑  收藏
虽然将jxl.jar包添加到工程里了, 但是仍让有java.lang.ClassNotFoundException: jxl.write.WritableCell错误。
需要把jar包放在web-inf/lib目录下再加载才可以解决这个问题。
package tony.servlet.example;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class Hello extends HttpServlet {
    protected void service(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // ServletOutputStream out = response.getOutputStream();
        // PrintWriter out = response.getWriter();
        // out.println("Hello world!");
        // System.out.println("TEST");
        // request.getRequestDispatcher("/WEB-INF/jspfooder/test1.html").forward(request,
        // response);
        // request.getRequestDispatcher("test.jsp").forward(request, response);
        // request.getRequestDispatcher("/WEB-INF/test.jsp").forward(request,
        // response);
        /*
         * response.setContentType("application/vnd.ms-excel");
         * response.setHeader("Content-disposition","filename="+ "Example.xls"
         * ); HSSFWorkbook demoWorkBook = new HSSFWorkbook(); HSSFSheet sheet =
         * demoWorkBook.createSheet("账号详单"); HSSFRow row = sheet.createRow(0);
         * HSSFCell cell = row.createCell(0); cell.setCellValue(11);
         * ServletOutputStream out = response.getOutputStream();
         * demoWorkBook.write(out); out.flush(); out.close();
         */
        OutputStream out = response.getOutputStream();
        try {

            response.setContentType("application/vnd.ms-excel");

            response.setHeader("Content-Disposition",
                    "attachment; filename=example.xls");

            WritableWorkbook w = Workbook.createWorkbook(out);
            WritableSheet s = w.createSheet("sheet1", 0);

            s.addCell(new Label(0, 0,
                    "this is my first servlet & sheet example."));
            w.write();
            w.close();

        } catch (Exception e) {
            throw new ServletException("Exception in Excel Sample Servlet", e);
        } finally {
            if (out != null)
                out.close();
        }
    }
}


Feedback

# re: Servlet 利用jxl访问excel  回复  更多评论   

2012-11-22 11:35 by 八婆本
草尼马,瞎jb写的程序别拿出来献丑好么

只有注册用户登录后才能发表评论。


网站导航: