动态生成Excel到客户端

    /**
	 * 生成文件
	 * @param tempList  数据源
	 * @param title    Excel第一行表头
	 * @param fileName 文件名称
	 * @param hm
	 * @throws Exception
	 */
	public static void tempExcel(List<Object[]> tempList , String title[], String filename,
			HttpServletResponse response) throws Exception {
		String oldFileName = filename; 
		filename = new String(filename.getBytes(), "ISO8859-1");   //此处不转码页面弹出的下载框就会乱码
		try {              //页面弹出下载框
              response.reset();// 清空输出流   response.setContentType("application/vnd.ms-excel");// 定义输出类型  response.addHeader("Content-Disposition", "attachment;filename="+ filename+".xls"); //设定输出文件头   // 创建Excel工作薄 OutputStream os = response.getOutputStream();// 取得输出流  WritableWorkbook wwb = Workbook.createWorkbook(os);// 建立excel文件   // 添加第一个工作表并设置第一个Sheet的名字 int count = (tempList.size() / 60000) + 1; //一张sheet最多存储65536条数据(2^16) for (int j = 1; j <= count; j++) { WritableSheet sheet = wwb.createSheet(oldFileName.trim() + String.valueOf(j), j - 1); Label label; // Label(x,y,z) 代表单元格的第x+1列,第y+1行, 内容z for (int i = 0; i < title.length; i++) { // 在Label对象的子对象中指明单元格的位置和内容 label = new Label(i, 0, title[i]); // 将定义好的单元格添加到工作表中 sheet.addCell(label); } int formRow = (j - 1) * 60000 + 1; int toRow = j * 60000; if (count == j) { toRow = tempList.size() % 60000; } for (int r = formRow; r <= toRow; r++) { Object[] obj = tempList.get(r - 1); for (int c = 0; c < obj.length; c++) { if (obj != null) { String centent = String.valueOf(obj[c]); label = new Label(c, r, centent); sheet.addCell(label); } } } } // 写入数据 wwb.write(); // 关闭文件 wwb.close(); response.flushBuffer(); } catch (Exception e) { System.out.println("生成Excel时出错:"); e.printStackTrace(); } }

  需要导入jxl.jar

  1. 页面需要导入的包

    import java.io.OutputStream;
    import java.util.List;

    import javax.servlet.http.HttpServletResponse;

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

  2. 把生成的excel数据输出到response的OutputStream
     wwb.write();
       wwb.close();
       response.flushBuffer();

参考资料:http://www.blogjava.net/netnova/archive/2009/07/28/146776.html

原文地址:https://www.cnblogs.com/Jenny-sider/p/4026231.html