表单/ajax上传excel文件

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>
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值