struts2+ajaxSubmit+poi导入excel

form表单

<form id="upLoadForm"  style="margin-bottom:3">
		<input type="hidden" name="hasGrupRole" value="<s:property value='hasGrupRole'/>">
	    <table width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="#a8c7ce" οnkeypress="enterQuery()">
	       <tr>
	       	 <td class="table_head_td" align="center">上传:</td>
	         <td class="table_head_td" ><input id="excelFile" name="files" type="file"/></td>
	       </tr>
	       <tr>
	       	 <td class="table_head_td" align="center" colspan="2">
	       	 <input type="button" value="提交" accesskey="M"  title="ALT+M" class="btn0" οnclick="submitExcel();"/>
	       	 </td>
	       </tr>
	    </table>
</form>

js

function submitExcel(){
	if(confirm('确定上传数据!')){
    	var excelFile = $("#excelFile").val();
        if(excelFile=='') {
            alert("请选择需上传的文件!");
            return false;
        }
        if(excelFile.indexOf('.xls')==-1){
            alert("文件格式不正确,请选择正确的Excel文件(后缀名.xls)!");
            return false;
        }

		$("#upLoadForm").ajaxSubmit({
			   type: "POST",
			  encType:'multipart/form-data',
			   url: '提交路径',
			   data:{
					'files':excelFile//  files action定义属性   File类型
			 	   },
			   success: function(data){
					   alert(data);//返回值

		});
		return false;//如不返回false会跳转页面
	}
}
action

public void doUpload(){
		try{
			try {
				this.service.doUpLoad(model);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}finally{
//			Struts2Utils.getResponse().setContentType("text/xml;charset=utf-8");//返回值报错
			Struts2Utils.getResponse().setHeader("Content-type", "text/html;charset=UTF-8");//如不设置头信息会中文会出现火星文类型乱码
			Struts2Utils.getResponse().setCharacterEncoding("UTF-8"); //如不设置编码类型中文会出现‘?????’乱码
			try {
				Struts2Utils.getResponse().getWriter().print(this.getModel().getMessage());//打印返回值传至前端
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}


service
public void doUpLoad(TransCenterModel model) throws Exception{
		 // 检查后缀名是否符合条件,同时更改上传文件的文件名 
        int filesize = model.getFilesFileName().length(); 
        String fileEx = model.getFilesFileName().substring( 
        		model.getFilesFileName().indexOf("."), filesize); 
        //获取文件名 
//        String fileName=model.getFilesFileName().substring(0,model.getFilesFileName().indexOf(".")); 
        // 获得上传路径 
        String realPath = ServletActionContext.getServletContext().getRealPath( 
                "/UploadFile/"); 
        File saveFile=null; 
        ArrayList<ArrayList<String>> row=null;
        if (model.getFiles() != null) { 
            saveFile = new File(new File(realPath), model.getFilesFileName()); 
            if (!saveFile.getParentFile().exists()) { 
                saveFile.getParentFile().mkdirs(); 
            } 
 
            FileUtils.copyFile(model.getFiles(), saveFile);// 到这里,文件已上传成功
            if (fileEx.equals(".xls") || fileEx.equals(".xlsx")) { 
            	String files=saveFile.getPath();
            	String excel=files.substring(files.lastIndexOf("\\")).substring(1);
            	files=files.substring(0, files.lastIndexOf("\\"));
            	files=files.replaceAll("\\\\","\\\\\\\\");
        		row=readExcel(excel,files);
            }<pre name="code" class="java"><span>	</span>    <span>for (ArrayList<String> cell : row) {
        <span>		</span>/</span>/数据处理
<span>	</span>    }

}
 
        this.addMessages(model, "trans.upload.succ",new String[]{});
}
@SuppressWarnings("deprecation")
public ArrayList<ArrayList<String>> readExcel(String fileName,String path) {   
        ArrayList<ArrayList<String>> Row =new ArrayList<ArrayList<String>>();   
           
        try {   
        	Workbook workBook = null;  
        	 try {   
             	workBook = new XSSFWorkbook(path+"\\"+fileName);   
             } catch (Exception ex) {   
             	workBook = new HSSFWorkbook(new FileInputStream(path+"\\"+fileName));   
             }  
               
            for (int numSheet = 0; numSheet < workBook.getNumberOfSheets(); numSheet++) {   
                Sheet sheet = workBook.getSheetAt(numSheet);   
                if (sheet == null) {   
                    continue;   
                }   
                // 循环行Row   
                for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {   
                    Row row = sheet.getRow(rowNum);   
                    if (row == null) {   
                        continue;   
                    }   
                    // 循环列Cell   
                    ArrayList<String> arrCell =new ArrayList<String>();   
                    for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {   
                        Cell cell = row.getCell(cellNum);   
                        if (cell == null) {   
                            continue;   
                        }   
                        arrCell.add(getValue(cell));   
                    }   
                    Row.add(arrCell);   
                }  
            }   
        } catch (IOException e) {   
            System.out.println("e:"+e);   
        }   
       
        return Row;   
    }
	 private String getValue(Cell cell) {   
		 	cell.setCellType(Cell.CELL_TYPE_STRING);
		 	return cell.toString();
	  } 






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值