java实现excel导出实例

声明下:list是前面操作查询的结果集。

String path = request.getSession().getServletContext().getRealPath("/");
		String name = "测试_" + Tools.getDateStr(new Date(), "YYYYMMddHHmmss") + ".xls";

		XLSTransformer transformer = new XLSTransformer();
		String sfrom = path + "/xlstemplet/" +(1 == salvationType?"名字1-":"名字2-")+ "测试.xls";// 模板文件
		Workbook workbook;

		int pageSize = (!Tools.isEmpty(request.getParameter("pageSize"))) ? Integer.parseInt(request.getParameter("pageSize"))
				: 100;// 每个sheet的记录数量
		try {
			if ("mutiSheet".equals(request.getParameter("mutiSheet"))&& list.size() / pageSize > 1) {

				List sheetObjects = new ArrayList(); // 每一个sheet对应的list
				List sheetNames = new ArrayList(); // 每一个sheet名

				if (list != null) {
					for (int i = 0; i < list.size() / pageSize; i++) {
						Map subMap = new HashMap();
						subMap.put("pageSize", pageSize);
						subMap.put("currentPage", (i+1));
						int k = ((i + 1) * pageSize < list.size()) ? (i + 1) * pageSize : list.size();
						List resultList = list.subList(i * pageSize, k);
						subMap.put("resultList", resultList);
						sheetObjects.add(subMap);
						sheetNames.add("page" + (i + 1));
					}
				}
				workbook = transformer.transformMultipleSheetsList(new FileInputStream(sfrom), sheetObjects, sheetNames, "map",
						new HashMap(), 0);
			} else {
				Map beanMap = new HashMap();
				map.put("pageSize", 0);
				map.put("currentPage",0);
				beanMap.put("map", map);
				workbook = transformer.transformXLS(new FileInputStream(sfrom), beanMap);
			}
			response.reset();
			response.setHeader("Content-disposition", "attachment;success=true;filename =" + URLEncoder.encode(name, "utf-8"));
			OutputStream fos = null;
			fos = response.getOutputStream();
			workbook.write(fos);
			fos.flush();
			fos.close();
		} catch (ParsePropertyException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

 另外需要引入3个jar包:这蛋疼的博客不能传附件。。。

3个jar文件的下载地址:http://download.csdn.net/detail/sky_xin/8444825

你可能感兴趣的:(java实现)