servlet简单的导入导出EXCEL


public String exp(){

HttpServletResponse response = (HttpServletResponse)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
	        response.setContentType("application/vnd.ms-excel;charset=utf-8");
	        response.addHeader("Content-Disposition", "attachment;filename=Test.csv");
	        List<Test> list=page.getDataList();
	        DataOutputStream stream=new  DataOutputStream(response.getOutputStream());
	        String content="名称, 二维码, 状态,创建时间,主题数量,推广量\n";
	        stream.write(content.getBytes("GBK"));
	        for (Test test : list) {
	        	content=test.getName()+","+test.getCode()+","+test.getStatus().getDisplayName()+","+test.getCreateTime()+","+test.getTopicSize()+","+test.getPopularize()+"\n";
	        	stream.write(content.getBytes("GBK"));
			}
	        stream.flush();
		} catch (Exception e) {
			log.error(e);
		}
		return null;
	}

	public String imp(){
		BufferedReader in =null;
		try {
			if(upLoadFile!=null){
				if(upLoadFile.getName().indexOf(".csv")==-1){
					this.setMessage("错误的数据文件,请重新选择文件!");
					list();
				}
				String line;
				in = new BufferedReader(new FileReader(upLoadFile));
				List<Test> batch=new ArrayList<Test>();
				line = in.readLine();
				while((line = in.readLine()) != null){
					Test tmp=new Test();
					tmp.setCreateTime(TimeUtil.getCurrentDateTime());
					tmp.setStatus(Test.Status.PENDING);
					tmp.setTimes(0);
					String[] datas=line.split(",");
					if(datas!=null&&datas.length>0){
						tmp.setName(datas[0]);//FIXME the format of data
						tmp.setCode(datas[1]);
					}
					batch.add(tmp);
				}
			}
		} catch (Exception e) {
			log.error("Update load file error:", e);
			
		}finally{
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
				in = null;
			}
		}

	}

猜你喜欢

转载自ahua186186.iteye.com/blog/2102096
今日推荐