springmvc Excel文件上传,使用ajaxSubmit方法进行文件上传,使用弹出层弹出一个框(jquery layer),点击进行下载

7 篇文章 0 订阅

效果:


弹出层使用的是jquery插件layer  插件下载地址http://download.csdn.net/detail/rendeyishi/8048139

因为我是使用的是jquery里面的ajaxSubmit进行文件上传 所以这个jquery.form.js必须存在

还需要的js文件是:layer.min.js jquery-1.7.2.js


例子script代码:

 <a href="javascript:void(0);" id="import" class="easyui-linkbutton" >Excel导入</a>

$('#import').on('click', function(){
               var pageii = $.layer({
                    type: 1,
                    title: false,
                    area: ['auto', 'auto'],
                    border: [0], //去掉默认边框
                    closeBtn: [0, false], //去掉默认关闭按钮
                    shift: 'left', //从左动画弹出
                    page: {
                        html: '<div style="width:420px; height:260px; padding:20px; border:1px solid #ccc; background-color:#eee;">'+
                                    '<button type="button" id="download">下载Excel模板</button><button id="pagebtn" class="btns" οnclick="">关闭</button>'+
                                    '<form  id="upload" enctype="multipart/form-data" action="${basePath}/payment/importBuildInfoExcel.html" method="post">'+
                                          ' <input name="fileBuildInfo" id="fileBuildInfo" class="big"  type="file" />'+
                                           '<input type="button" id="importBuildInfo"class="btns" value="导入"/>'+
                                  ' </form>'+
                               '</div>'
                    }
               });
               //自设关闭
               $('#pagebtn').on('click', function(){
                   layer.close(pageii);
               });
               //点击导入的时候触发的事件
               $('#importBuildInfo').on('click',function(){
                    if($('#fileBuildInfo').val()==""){
                        alert("请先选择要上传的房屋信息文件!");
                    }else{
                      $('#upload').ajaxSubmit({
                              url:"${basePath}/payment/importBuildInfoExcel.html",
                            cache:false,
                            dataType:'json',
                            success: function(data) {
                                if(data.result!=null){
                                   $.each(data.result,function(i,value){
                                       alert(value);
                                   });
                                }
                            } ,
                            error:function(){
                                alert("error");
                            }
                      });
                 }
               });
               //下载excel模板
               $('#download').on('click',function(){
                       location.href="${basePath}/payment/downloadInfo.html";               
               });
            });

下载模板的方法

/**
* 下载房屋信息模板
* @author ljr
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/downloadInfo")
@ResponseBody
public void download(HttpServletRequest request,HttpServletResponse response) throws Exception {  
       response.setContentType("text/html;charset=UTF-8");   
       BufferedInputStream in = null;  
       BufferedOutputStream out = null;  
       request.setCharacterEncoding("UTF-8");  
       String separator = File.separator;
       String rootpath = request.getSession().getServletContext().getRealPath(separator+"upload");  
       String fileName = "ImportTemplate.xlsx";
  
       try {  
           File f = new File(rootpath + separator + fileName);  
           response.setContentType("application/x-excel");  
           response.setCharacterEncoding("UTF-8");  
             response.setHeader("Content-Disposition", "attachment; filename="+fileName);  
           response.setHeader("Content-Length",String.valueOf(f.length()));  
           in = new BufferedInputStream(new FileInputStream(f));  
           out = new BufferedOutputStream(response.getOutputStream());  
           byte[] data = new byte[1024];  
           int len = 0;  
           while (-1 != (len=in.read(data, 0, data.length))) {  
               out.write(data, 0, len);  
           }  
       } catch (Exception e) {
        logger.error("下载房屋信息模版异常:",e);
       } finally {  
           if (in != null) {  
               in.close();  
           }  
           if (out != null) {  
               out.close();  
           }  
       } 
      
   }  

因为我文件上传我使用的springmvc:

所以配置:

<bean  id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="20000000"/>
    </bean>

文件上传代码:

    @RequestMapping("/importBuildInfoExcel")
    @ResponseBody
    public DefaultResult importBuildInfoExcel(@RequestParam(value="fileBuildInfo",required=false) MultipartFile buildInfo,HttpServletRequest request,HttpServletResponse response){
        try {
            if (buildInfo != null) {
                String path = request.getSession().getServletContext().getRealPath("/upload")+"/"+buildInfo.getOriginalFilename();
                File file=ToolKit.getFileFromBytes(buildInfo.getBytes(), path);//需要先保存在本地
                List<BuildInfo> list=BuildInfoExcel.importBuildInfo(file, request);//这里是解析excel文件
                DefaultResult dr=buildInfoService.insertBuildInfoCommunity(list, logger);//这里做的是一个插入数据库功能
                if(dr.getResult()!=null){
                    List<String> returnList=(List<String>) dr.getResult();
                    for (String s : returnList) {
                        logger.info(s);
                    }
                }
                ToolKit.deleteFile(path);
                return dr;
            }
        } catch (IOException e) {
            logger.error("导入房屋信息报错:",e);
        }
        return null;
    }

解析excel的代码

public static List<BuildInfo> importBuildInfo(File file ,HttpServletRequest request){
        try {
            // 创建需要批量插入数据集合
            List<BuildInfo> list = new ArrayList<BuildInfo>();
            // 创建一个FileInputStream 文件输入流
            FileInputStream inputStream = new FileInputStream(file);
            // 创建对Excel工作簿文件的引用
            Workbook wookbook = null;
            String name = file.getName();
            String fileType = name.substring(name.lastIndexOf(".") + 1,
                    name.length());
            if (fileType.equals("xlsx")) {
                wookbook = new XSSFWorkbook(inputStream);
            } else if (fileType.equals("xls")) {
                wookbook = new HSSFWorkbook(inputStream);
            }
            // 在Excel文档中,第一张工作表的缺省索引是0
            Sheet sheet = wookbook.getSheetAt(0);
            // 获取到Excel文件中的所有行数
            int rows = sheet.getPhysicalNumberOfRows();
            // 遍历行 从第二行开始遍历
            for (int i = 1; i < rows; i++) {
                // 读取左上端单元格
                Row row = sheet.getRow(i);
                // 行不为空
                if (row != null) {
                    // 创建对象
                    BuildInfo object = new BuildInfo();
                    object.setRow(i+1);
                    object.setCommunityName((row.getCell(0)
                            .getStringCellValue()).trim());// 获取小区名称
                    object.setHomeAddress((row.getCell(1).getStringCellValue())
                            .trim());// 获取房屋信息
                    // 设置姓名
                    Cell nameCell = row.getCell(2);
                    if (nameCell != null && !nameCell.equals("")) {
                        nameCell.setCellType(Cell.CELL_TYPE_STRING);
                        String bname = nameCell.getStringCellValue().trim();
                        if (bname != null && StringUtils.isEmpty(bname)) {
                            object.setName(bname);
                        }
                    }
                    // 设置性别
                    Cell sexCell = row.getCell(3);
                    if (sexCell != null && !sexCell.equals("")) {
                        sexCell.setCellType(Cell.CELL_TYPE_STRING);
                        String sex = sexCell.getStringCellValue().trim();
                        if(sex.equals("男")|| sex.equals("女")){
                            object.setSex(sex);
                        }
                        
                    }
                    Cell homeAreaCell = row.getCell(4);
                    if (homeAreaCell != null && !homeAreaCell.equals("")) {
                        homeAreaCell.setCellType(Cell.CELL_TYPE_STRING);
                        String homeAreaString = homeAreaCell
                                .getStringCellValue().trim();
                        if (!homeAreaString.equals("")) {
                            try {
                                Float homeArea = Float
                                        .parseFloat(homeAreaString);
                                object.setHomeArea(homeArea);
                            } catch (NumberFormatException e) {
                                object.setHomeArea(null);
                            }
                        }
                    }
                    Cell mobileCell = row.getCell(5);
                    if (mobileCell != null && !(mobileCell.equals(""))) {
                        mobileCell.setCellType(Cell.CELL_TYPE_STRING);
                        String mobile = mobileCell.getStringCellValue().trim();
                        if (!mobile.equals("")) {
                            object.setPhone(mobile);
                        }
                    }
                    // 将对象增加到集合中
                    list.add(object);
                }
            }
            // 返回集合
            return list;
        } catch (IOException e) {
            logger.error("创建导入excel对象报错!", e);
        }
        return null;
    }

//根据byte[]获取file

/**
     * 根据字节数组获取File
     * @param b 字节数组
     * @param outputFile 输出的路径(保存路径)
     * @return
     */
    public static File getFileFromBytes(byte[] b, String outputFile) {
        BufferedOutputStream stream = null;
        File file = null;
        try {
        file = new File(outputFile);
             FileOutputStream fstream = new FileOutputStream(file);
             stream = new BufferedOutputStream(fstream);
             stream.write(b);
         } catch (Exception e) {
             logger.error("文件保存出错",e);
        } finally {
            if (stream != null) {
                 try {
                    stream.close();
                 } catch (IOException e1) {
                     logger.error("文件流关闭出错",e1);
                }
            }
        }
         return file;
     }



poi解析excel功能参数说明 此项目是基于springMVC实现的,基本流程为从前台jsp页面使用Ajax文件上传导入excel文件(.xls(97-03)/.xlsx(07以后)),传到后台controller调用相应工具类解析后返回指定参数做后续处理. 1. POIUtil.java工具类 解析通过MutilpartFile导入的Excel并解析里面数据,先判断文件的类型(excel处理有两种此处为两种通用)是.xls/.xlsx,通过workbook.getNumberOfSheets()获取工作簿数量,遍历工作簿,sheet.getLastRowNum()获取最大行数,将每行数据放入List list = new Array List(),并根据excel数据类型将器转换为字符串、数字、Boolean、公式、空值类型防止现错误,最后返回一个list. 2. ExcelUtil.java工具类 解析通过MutilpartFile导入的Excel并解析里面数据,先判断文件的类型(excel处理有两种此处为两种通用)是.xls/.xlsx,采用Apache的POI的API来操作Excel,读取内容后保存到List中,再将List转Json(使用Linked,增删快,与Excel表顺序保持一致),Sheet表1————>List1<Map> 步骤1:根据Excel版本类型创建对于的Workbook以及CellSytle 步骤2:遍历每一个表中的每一行的每一列,这里做了些小改动,因为后续可能解析过后可能会保存入数据库,这里为第一行数据添加一个自定义表头 String[] p = new String[]{"name","age","sex","tel","address","e-mail","phone"}; 遍历的列数量以p的length为准 步骤3:一个sheet表就是一个Json,多表就多Json,对应一个 List 一个sheet表的一行数据就是一个 Map 一行中的一列,就把当前列头为key,列值为value存到该列的Map中 Map 一个线性Hash Map,以Excel的sheet表顺序,并以sheet表明作为key,sheet表转换Json后的字符串作为value 最后返回一个LinkedHashMap 3. ExcelToJsonPoi.java工具类 这个与上面工具类类似,不过这个是解析本地excel文件不是使用的流,使用迭代遍历sheet工作簿与每行每列的值,将所有类型作为String类型处理返回一个json对象输至控制台
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值