JXL导出数据到excel

本文提供了一个使用Java实现从数据库列表数据导出至XLS文件的实例代码,包括了设置响应头、生成临时文件及读取输出的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      上篇写了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;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值