表单/ajax上传excel文件

来源:互联网 发布:hibernate源码分析 编辑:程序博客网 时间:2024/06/07 03:48

form表单提交:

<form id="upload-form" method="post" action="/import" enctype="multipart/form-data">    <div>        <input type="file" name="excelfile" id="excelfile"/>        <input type="hidden" name="fileType" value="10"/>    </div>    <input type="submit"  id="upload" value="上传"/></form>

ajax异步上传:

<form id="upload-form" method="post" action="/import" enctype="multipart/form-data">    <input type="file" name="excelfile" id="excelfile" value="" />    <input type="hidden" name="fileType" value="10">    <input type="button"  id="upload" value="上传"/></form>js:    $("#upload").click(function(){        var formdata = new FormData(document.getElementById("upload-form"));        $.ajax({            url:"/import",            type:"post",            data:formdata,            contentType:false, //- 必须false才会自动加上正确的Content-Type            processData: false, //- 必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理            success:function(){                alert("ok");            },            error:function(){                alert("fail");            }        });    });

后台代码:

    @RequestMapping(value = "/import")    public ModelAndView importExcel(@RequestParam(value = "excelfile") MultipartFile file, String fileType,         HttpServletRequest request){        try {            List<Map> list = readExcelFile(file);        } catch (Exception e) {            e.printStackTrace();        }        ModelAndView mv = new ModelAndView("search");        return mv;    }    private List<Map> readExcelFile(MultipartFile file) throws Exception {        String fileName = file.getOriginalFilename();//获取文件名        long size = file.getSize();        String format = fileName.substring(fileName.lastIndexOf(".")+1);        System.out.println("文件名:"+fileName+",大小:"+size/1024+"kb,格式:"+format);        Workbook workbook = null;        InputStream inputStream = file.getInputStream();        //- excel 2003        if("xls".equals(format)){            workbook = new HSSFWorkbook(inputStream);        }else if ("xlsx".equals(format)){            workbook = new XSSFWorkbook(inputStream);        }else {            throw new Exception("文件格式非法!");        }        /** 读取第一个sheet */        List<Map> result = new ArrayList<>();        int sheets = workbook.getNumberOfSheets();        if(sheets > 0){            Sheet sheet = workbook.getSheetAt(0);            result = readSheet(sheet);        }        inputStream.close();        return result;    }    /**     * 解析sheet.     *     sheet前三列分别为对应到bean的字段、字段类型、excel表头     *     * @param sheet     * @return     */    private List<Map> readSheet(Sheet sheet) {        List<Map> result = new ArrayList<Map>();        int totalRows = sheet.getPhysicalNumberOfRows();//- Excel行数        int totalCells = 0;//- Excel列数        String[] fields = null; //- 存储对应bean的字段名称        Row firstRow = sheet.getRow(0);        if (totalRows > 0 && firstRow != null) {            totalCells = firstRow.getPhysicalNumberOfCells();            fields = new String[totalCells];            for (int c = 0; c < totalCells; c++) {                fields[c] = firstRow.getCell(c).getStringCellValue();            }        }else            return result;        /** 循环Excel的行, 第四行是正文开始 */        for (int r = 4; r < totalRows; r++) {            Row row = sheet.getRow(r);            if (row == null){                continue;            }            Map map = new HashMap();            /** 循环Excel的列 */            for (int c = 0; c < totalCells; c++) {                Cell cell = row.getCell(c);                if (null != cell) {                    //- cell是数值类型                    if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){                        map.put(fields[c], cell.getNumericCellValue());                    }                    //- cell是字符串类型                    else if(cell.getCellType() == HSSFCell.CELL_TYPE_STRING){                        map.put(fields[c], cell.getStringCellValue());                    }                }            }            result.add(map);        }        return result;    }

处理excel的maven依赖:

    <dependency>       <groupId>org.apache.poi</groupId>        <artifactId>poi</artifactId>        <version>3.12</version>        <exclusions>            <exclusion>                <artifactId>commons-codec</artifactId>                <groupId>commons-codec</groupId>            </exclusion>        </exclusions>    </dependency>    <dependency>        <groupId>org.apache.poi</groupId>        <artifactId>poi-ooxml</artifactId>        <version>3.12</version>    </dependency>
原创粉丝点击