springmvc poi excel

本文使用的工具类参考了 http://raising.iteye.com/blog/2232167 这篇文章,由于报错做了改动,在此感谢原作者。
项目源码地址:https://github.com/zmdstr/demo
maven pom

        <!-- poi -->
        <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>3.14</version>
        </dependency>
        <!-- 文件上传 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>file upload</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/ajaxfileupload.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/file-upload.js"></script>
</head>
<body>
<h3>批量导入excel测试</h3>
    <form action="">
        <input type="file" id="file" name="file"/>
        <input type="button" value="导入数据" onclick="upload()">
    </form>
</body>
</html>

file-upload.js

function upload(){
    console.log("点击上传按钮");
    $.ajaxFileUpload({  
        url : "upload1",  
        //dataType : 'json',  
        secureuri : false,  
        fileElementId : 'file',  
        success : function(res, status) { //服务器成功响应处理函数  
            if (status) {  
                console.log(status);
            }},
            error : function(res, status, e) {//服务器响应失败处理函数  
                alert("导入数据异常:文件导入过程异常。");  
            }  
        });  
}

springmvc.xml中需要增加的配置

<!-- 文件上传配置 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 文件的最大上传大小 -->
        <property name="defaultEncoding" value="UTF-8" />
        <property name="maxUploadSize" value="1058576000" />
        <property name="uploadTempDir" value="/uploadFile/temp/" />
    </bean>

controller

@RequestMapping("/upload")
    public @ResponseBody String fileUpload(@RequestParam(value = "file") MultipartFile excelFile) {
        InputStream inputStream = null;
        String flag = "导入成功!";
        try {
            inputStream = excelFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            flag = "导入失败";
        }
        List<Map<String, String>> excel = ExcelImportUtil.parseExcel(inputStream);
        for (Map<String, String> row : excel) {
            String id = row.get("id");
            String tbUniversityName = row.get("tb_university_name");
            String tbUniLoc = row.get("tb_uni_loc");
            String tag1 = row.get("tag1");
            String tag2 = row.get("tag2");
            String tag3 = row.get("tag3");
            String tag4 = row.get("tag4");
            UniversityBaseInfo baseInfo = new UniversityBaseInfo();
            baseInfo.setId(Integer.valueOf(id));
            baseInfo.setTag1(tag1);
            baseInfo.setTag2(tag2);
            baseInfo.setTag3(tag3);
            baseInfo.setTag4(tag4);
            baseInfo.setTbUniLoc(tbUniLoc);
            baseInfo.setTbUniversityName(tbUniversityName);
            myService.insert(baseInfo);
        }
        return flag;
    }
}

ExcelImportUtils

public class ExcelImportUtil {
    public static List<Map<String, String>> parseExcel(InputStream fis) {
        List<Map<String, String>> data = new ArrayList<Map<String, String>>();
        try {
            HSSFWorkbook book = new HSSFWorkbook(fis);
            HSSFSheet sheet = book.getSheetAt(0);
            int firstRow = sheet.getFirstRowNum();
            int lastRow = sheet.getLastRowNum();
            for (int i = firstRow; i < lastRow; i++) {
                Map<String, String> map = new HashMap<String, String>();
                HSSFRow row = sheet.getRow(i);
                int firstCell = row.getFirstCellNum();
                int lastCell = row.getLastCellNum();
                for (int j = firstCell; j < lastCell; j++) {
                    HSSFCell cell2 = sheet.getRow(firstRow).getCell(j);
                    String key = cell2.getStringCellValue();
                    HSSFCell cell = row.getCell(j);
                    String val = "";
                    if (null != cell) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        }
                        val = cell.getStringCellValue();
                    }
                    // 如果是表头,不放入map
                    if (i == firstRow) {
                        break;
                    } else {
                        map.put(key, val);
                    }
                    // System.out.println(map);
                }
                // 剔除表头
                if (i != firstRow) {
                    // 载入一行数据
                    data.add(map);
                    System.out.println(map);
                }
            }
            System.out.println(data);
            book.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }
}

个人微信公众号,追寻自由,分享生活!
这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值