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入數據庫就不難了吧.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章