后台
@RequestMapping(value = "upload", method = RequestMethod.POST)
public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response,Model model) throws Exception {
/* JSONObject obj = new JSONObject();
PrintWriter pw = null;*/
String fileName = file.getOriginalFilename();
if(fileName==null||fileName==""||!fileName.endsWith(".xls")){
throw new Exception("上传文件为空或者类型错误");
}
//保存
try {
fileName=Long.toString(System.currentTimeMillis())+fileName;
System.out.println(path);
model.addAttribute("path", path);
model.addAttribute("fileName", fileName);
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
/ *pw = response.getWriter();
obj.put("msg", "1");
pw.print(obj);*/
file.transferTo(targetFile);
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
} /*finally{
if(pw!=null){
pw.close();
}
}*/
//创建一个list 用来存储读取的内容Workbook rwb = null;
Cell cell = null;
//创建输入流
InputStream stream = new FileInputStream(path+"/"+fileName);
//获取Excel文件对象
rwb = Workbook.getWorkbook(stream);
//获取文件的指定工作表 默认的第一个
Sheet sheet = rwb.getSheet(0);
List<CmerEveitemVo> beans=new ArrayList<CmerEveitemVo>();
CmerEveitemVo vo = new CmerEveitemVo();
//行数(表头的目录不需要,从1开始)
for(int i=1; i<sheet.getRows(); i++){
//创建一个数组 用来存储每一列的值
String[] str = new String[sheet.getColumns()];
//列数
for(int j=0; j<sheet.getColumns(); j++){
//获取第i行,第j列的值
cell = sheet.getCell(j,i);
str[j] = cell.getContents();
System.out.print(str[j]);
if(j==0){
vo.setTbitem(str[j]);
}if(j==1){
vo.setDefitem40(str[j]);
}if(j==2){
vo.setCostcenter(str[j]);
}if(j==3){
BigDecimal bd=new BigDecimal(str[j]);
vo.setYbje(bd);
}if(j==4){
vo.setDigest(str[j]);
}
}
//把刚获取的列存入list
beans.add(vo);
}
model.addAttribute(REQUEST_BEANS, beans); //把结果集放入request
model.addAttribute(REQUEST_WRITE_BACK_FORM_VALUES, RmVoHelper.getMapFromRequest((HttpServletRequest) request)); //回写表单
return "sx/exp/insertCmerExpbill";
}
前台
function upload_onClick(){
form1.action="<%=request.getContextPath()%>/cmerexpbill/upload";
form1.submit();
}
ajax前台
function upload_onClick(){
$("#form1").ajaxSubmit({
type : "POST",
url : "<%=request.getContextPath()%>/cmerexpbill/upload",
dataType: "json",
success: function(data){
if(data.msg=='1'){
alert('添加成功');
}},
error : function() {
alert("文件为空或格式错误");
}
});
}