以excel的方式下载文件

这是servlet端的代码

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String doid = request.getParameter("doid");
		String dbname = request.getParameter("dbname");

		//Tools dbnametool = new Tools();//有些数据库的显示值和参数值不匹配,调用这个方法更新这个问题。
	    //String mydbname = dbnametool.ChangeDbName(dbname);
	    
		DBDao dbdao = new DBDao();
		List<List<String>> resultlist = dbdao.selectAllByIdDB(doid, dbname);//获得本页的所有数据
	    
		Do_aDao da_adao = new Do_aDao();//在do_a这个数据库里检索
	    int recordsnum = da_adao.selectNumByDoidDB(doid, dbname);
	    
		String doid_num = doid.substring(5);
		String filename = "DOID_"+doid_num+"_"+dbname+"_"+recordsnum;
		System.out.println(filename);
	
		OutputStream out = null;
		try {
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment; filename="+filename+".xls");

			//File file = new File("H:\\MyEclipse 8.x\\mymydbcrid\\WebRoot\\excel\\data.xls");// 注意,里面的参数必须是这个文件全路径
			String filePath=this.getServletConfig().getServletContext().getRealPath("/");
			File file = new File(filePath+"data.xls");//得到一个绝对路径
			
			Workbook srcBook = Workbook.getWorkbook(file);
			
			WorkbookSettings settings = new WorkbookSettings ();
            settings.setWriteAccess(null);
            
			WritableWorkbook wb = Workbook.createWorkbook(response
					.getOutputStream(), srcBook, settings);
			
			WritableSheet s = wb.getSheet(0); // w.createSheet("Demo", 0);

			
			int row = 0;
			WritableSheet sheet = wb.getSheet(0);
			for (int i = 0; i < resultlist.size(); i++) {
				row++;
				List<String> oneline = resultlist.get(i);
				for (int j = 0; j < oneline.size(); j++) {
					s.addCell(new Label(j, row - 1, oneline.get(j)));
				}
			}
			wb.write();
			wb.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null)
				out.close();
		}
		
	}

  下面是jsp端的一个简单的form

 <form id="form1" name="form1" method="post" action="EntityDownload">
                      <input name="doid" type="hidden" size="6" value=<%=doid%> />
                      <input name="dbname" type="hidden" size="6" value=<%=dbname%> />  
                      <input name="itemnum" type="hidden" size="6" value=<%=itemnum%> />
                      <input name="curpage" type="hidden" size="6" value=<%=curpage%> />  
                      This is the page <%=curpage %>, we have <%=pageCount %> pages records in total.&nbsp;&nbsp;&nbsp;<input type="submit" name="Submit" value="export all the data as xls file" />
                      </form><br/>

 

posted @ 2012-08-28 22:23  cloud_fish  阅读(455)  评论(0编辑  收藏  举报