1、后台类CreateXLS代码
package com.cys.j2ee.jxl; import java.io.*; import java.util.Collection; import javax.servlet.http.HttpServletResponse; import com.cys.j2ee.model.Person; import jxl.*; import jxl.write.*; public class CreateXLS { public static String ToExcel(HttpServletResponse response,String fileName,Collection<Person> persons){ try { OutputStream os = null; response.reset(); os = response.getOutputStream(); // 取得输出流 response.setHeader("Content-disposition","attachment; filename="+ new String(fileName.getBytes(), "ISO-8859-1")); // 设定输出文件头 response.setContentType("application/msexcel"); // 定义输出类型 WritableWorkbook book =Workbook.createWorkbook(os); // 生成名为“第一页”的工作表,参数0表示这是第一页 WritableSheet sheet = book.createSheet("用户表", 0); // 在Label对象的构造子中指名单元格位置是第一列第一行(0,0) // 以及单元格内容为test Label label = new Label(0, 0, "用户ID"); // 将定义好的单元格添加到工作表中 sheet.addCell(label); label = new Label(1, 0, "用户名"); // 将定义好的单元格添加到工作表中 sheet.addCell(label); label = new Label(2, 0, "密码"); // 将定义好的单元格添加到工作表中 sheet.addCell(label); int i=1; for (Person person : persons) { Label label2=new Label(0, i, person.getId()); sheet.addCell(label2); label2=new Label(1, i, person.getUserName()); sheet.addCell(label2); label2=new Label(2, i, person.getPassWord()); sheet.addCell(label2); i++; } // 写入数据并关闭文件 book.write(); book.close(); return "refresh"; } catch (IOException ex) {// 捕捉异常 System.out.println("流操作错误:" + ex.getMessage()); return ""; } catch (Exception e) { System.out.println(e); return ""; } } }
前台调用jsp代码:
<%@page import="java.io.IOException"%> <%@page import="java.io.OutputStream"%> <%@page import="java.util.Collection"%> <%@page import="com.cys.j2ee.dao.PersonDao"%> <%@page import="com.cys.j2ee.jxl.CreateXLS"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String action =request.getParameter("action"); if("3".equals(action)) { PersonDao dao=new PersonDao(); CreateXLS.ToExcel(response,"用户表.xls", dao.getPersons()); } %>