java简单实现excel单列数据解析存库&页面回显

java简单实现excel单列数据解析存库&页面回显

  • 配置:springMVC配置文件中需要添加:
<!-- 需要文件上传功能时,启用以下配置 -->
<bean id="multipartResolver"            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxInMemorySize">
        <value>1638400</value>
    </property>
</bean>
  • jsp代码 一个file添加一个change事件就好(简洁的来哈,只要引入一个jquery库即可)
  <body>
    <h3>测试导入</h3><hr/>
    <input id="file" type="file">
    <div id="showTb"></div>
  </body>

 <script type="text/javascript">
    $(function(){

        $("#file").change(function(){
            if($("#file").val()!=""){
                    if($("#file").val().indexOf(".xls")<0){
                        alert("文件格式有误");
                        $("#file").val("");
                        return false;
                    }

                    var formData=new FormData();
                    formData.append("file", $('#file')[0].files[0]);
                    $.ajax({
                        url: '${stx}/sixe/home!excelShow.do'+"?t="+Math.random(),
                        type: 'POST',
                        cache: false,
                        data: formData,
                        processData: false,
                        contentType: false,
                        async: false
                    }).done(function(data) {
                         //console.log(data);
                        if(data.code=="0"){
                            $("#showTb").empty();
                            var con = "<table><tr><td>导入手机号</td></tr>";

                            $.each( data.list, function(index,item){ 
                                con += "<tr><td>"+item+"</td></tr>";
                            });  
                            con += "</table>";
                            $("#showTb").append(con);
                        }else{
                            alert(data.message);
                        }
                    }).fail(function(res) {
                        console.log(res);
                        alert("上传失败!");
                        return false;
                        //$("#changeForm").modal({"data-backdrop":"static"});
                    });
            }
        });

    });

 </script>
  • controller代码
    @RequestMapping(value = "home!excelShow.do", method = RequestMethod.POST)
    @ResponseBody
    public Map<String ,Object> excelShow(HttpServletRequest request, HttpServletResponse response,
            MultipartFile file){
        Map<String ,Object> resultMap = new HashMap<String, Object>();
        if (!(file != null && (file.getOriginalFilename().toLowerCase().endsWith("xls")
                || file.getOriginalFilename().toLowerCase().endsWith("xlsx")))) {
            resultMap.put("code", "1");
            resultMap.put("message", "文件格式不正确!");
            return resultMap;
        }

        List<String> list= ExcelUtils.getPhones(file);
        for(String phone:list){
            System.out.println("导入:"+phone);
        }
        resultMap.put("code", "0");
        resultMap.put("list", list);
        resultMap.put("message", "解析成功");
        return resultMap;
    }
  • 解析excelUtils (重点在这)
package com.sixe.sixeApp.base.utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.web.multipart.MultipartFile;

public class ExcelUtils {

    public static List<String> getPhones(MultipartFile file){
        //File file = new File(path);
        List<String> set = new ArrayList<String>();
        try {
            /*if (!file.exists()) {
                return null;
            }*/
            // 输入流
            //InputStream inp = new FileInputStream(file);
            //Workbook wb = Workbook.getWorkbook(file.getInputStream());
            Workbook wb = WorkbookFactory.create(file.getInputStream());
            // 获得该工作区的第一个sheet
            Sheet sheet = wb.getSheetAt(0);

            // 总共有多少行,从0开始
            int totalRows = sheet.getLastRowNum() + 1;
            if (totalRows > 50000) {
                totalRows = 50000;
            }
            for (int i = 0; i < totalRows; i++) {
                // 取得该行
                Row row = sheet.getRow(i);
                // 注释的代码,是为了防止excel文件有空行
                if (row == null) {
                    continue;
                }
                double cellValue = 0.0;

                try {
                    cellValue = row.getCell(0).getNumericCellValue();
                } catch (Exception e) {
                    continue;
                }
                String mobile = new DecimalFormat("#").format(cellValue);

                if (mobile.length() != 11) {
                    continue;
                }

                set.add(mobile);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return set;
    }
}
  • 点击选择文件即可实现了(这里默认第一行为标题不会读取)
  • 这里保存数据库没写,已经解析出来了 保存list入数据库就不难了吧.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值