欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JXL导出数据到excel

程序员文章站 2024-02-24 12:48:58
...

      上篇写了JXL导入excel数据,有导入肯定有导出。直接贴代码

 

/**
	 * 列表数据导出到XLS文件
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward importReaderListToXls(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ReaderService rs = (ReaderService) this.getBean("readerService");
		PageBean pageBean = new PageBean();
		String pageStr = request.getParameter("page");
		if (pageStr != null) {
			pageBean.setCurrentPage(Integer.parseInt(pageStr));
		}

		ArrayList<ArrayList<String>> listAll = new ArrayList<ArrayList<String>>();
		List<ReaderBean> list = rs.getReaderList(pageBean);
		for (int i = 0; i < list.size(); i++) {
			ArrayList<String> tempList = new ArrayList<String>();
			ReaderBean readerBean = list.get(i);
			tempList.add(readerBean.getRecId().toString());
			tempList.add(readerBean.getReaderName().toString());
			listAll.add(tempList);
		}

		// 定义输出类型
		// response.setContentType("application/vnd.ms-excel");
		response.addHeader("Content-Disposition", "attachment;filename=" + new String("读者列表.xls".getBytes(), "ISO8859-1"));
		XlsTools xlsTools = new XlsTools();
		// 获取/upload文件夹在应用服务器绝对路径
		String dir = servlet.getServletContext().getRealPath("/temp");
		String tempFileName = "temp.xls";
		File target = new File(dir);
		if (target.exists() == false) {// 如果目录不存在,则创建这个目录
			target.mkdir();
		}
		String filePath = dir + "/" + tempFileName;
		log.debug(filePath);
		xlsTools.write(filePath);
		// 将生成的XLS先写到应用服务器绝对路径filePath下,然后再读这个文件并输出
		xlsTools.writeAll(listAll);
		xlsTools.closeWrite();
		ServletOutputStream output = response.getOutputStream();
		FileInputStream input = null;
		File file = new File(filePath);
		try {
			input = new FileInputStream(file);
			output = response.getOutputStream();
			byte size[] = new byte[1024];
			int length = 0;
			while ((length = input.read(size)) != -1) {
				output.write(size, 0, length);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			input.close();
			output.close();
		}
		return null;
	}