1. 程式人生 > >java spring maven excel 匯入

java spring maven excel 匯入

html

                            <div>fdafda
                                <form enctype="multipart/form-data" id="batchUpload" action="/visitor/import" method="post" class="form-horizontal">
                                    <button class="btn btn-success btn-xs" id="uploadEventBtn" style="height:26px;" type="button">選擇檔案</button>
                                    <input type="file" name="file" style="width:0px;height:0px;" id="uploadEventFile" />
                                    <input id="uploadEventPath" disabled="disabled" type="text" placeholder="請選擇excel表" style="border: 1px solid #e6e6e6; height: 26px;width: 200px;" />
                                </form>
                                <button type="button" class="btn btn-success btn-sm" onclick="excelImport.uploadBtn()">上傳</button>
                            </div>

 

js

/**
 * excel 匯入
 */
var ExcelImport = function() {
    this.init = function() {
        //模擬上傳excel
        $("#uploadEventBtn").unbind("click").bind("click", function() {
            $("#uploadEventFile").click();
        });
        $("#uploadEventFile").bind("change", function() {
            $("#uploadEventPath").attr("value",	$("#uploadEventFile").val());
        });
    };
    //點選上傳鈕
    this.uploadBtn = function() {
        var uploadEventFile = $("#uploadEventFile").val();
        if (uploadEventFile == '') {
            alert("請擇excel,再上傳");
        } else if (uploadEventFile.lastIndexOf(".xls") < 0) {//可判斷以.xls和.xlsx結尾的excel
            alert("只能上傳Excel檔案");
        } else {
            var url = "/visitor/import";
            var formData = new FormData($('form')[0]);
            excelImport.sendAjaxRequest(url, "POST", formData);
        }
    };
    this.sendAjaxRequest = function(url, type, data) {
        $.ajax({
            url : url,
            type : type,
            data : data,
            dataType : "json",
            success : function(result) {
                alert(result.message);
                Visitor.table.refresh();
            },
            error : function(result) {
                alert(result.message);
            },
            cache : false,
            contentType : false,
            processData : false
        });
    };
};
var excelImport;
$(function() {
    excelImport = new ExcelImport();
    excelImport.init();
});

controller

package com.stylefeng.guns.modular.server.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.modular.server.model.Park;
import com.stylefeng.guns.modular.server.service.IParkService;
import com.stylefeng.guns.modular.server.warpper.VisitorWarpper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.server.model.Visitor;
import com.stylefeng.guns.modular.server.service.IVisitorService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 訪客管理控制器
 *
 * @author
 * @Date 2018-09-27 17:30:18
 */
@Controller
@RequestMapping("/visitor")
public class VisitorController extends BaseController {

    private String PREFIX = "/server/visitor/";

    @Autowired
    private IVisitorService visitorService;

    @Autowired
    private IParkService parkService;

    /**
     * 跳轉到列表頁面
     */
    @Permission
    @RequestMapping("")
    public String index() {
        return PREFIX + "visitor.html";
    }

    /**
     * 分頁列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String visitorName) {
        Page<Map<String, Object>> page = new PageFactory<Map<String, Object>>().defaultPage();
        List<Map<String, Object>> result = visitorService.selectVisitorList(page, visitorName, page.getOrderByField(), page.isAsc());
        page.setRecords((List<Map<String, Object>>) new VisitorWarpper(result).warp());
        return super.packForBT(page);
    }

    /**
     * 跳轉到新增頁面
     */
    @RequestMapping("/visitor_add")
    public String visitorAdd(Model model) {
        List<Park> parkList = parkService.selectList(null);
        model.addAttribute("park_list",parkList);
        return PREFIX + "visitor_add.html";
    }

    /**
     * 新增
     */
    @Permission
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Visitor visitor) {
        visitor.setCreatetime(new Date());
        visitorService.insert(visitor);
        return SUCCESS_TIP;
    }

    /**
     * 跳轉到修改頁面
     */
    @RequestMapping("/visitor_update/{visitorId}")
    public String visitorUpdate(@PathVariable Integer visitorId, Model model) {
        Visitor visitor = visitorService.selectById(visitorId);
        model.addAttribute("item",visitor);
        Park park = parkService.selectById(visitor.getParkId());
        model.addAttribute("park",park);
        LogObjectHolder.me().set(visitor);
        return PREFIX + "visitor_edit.html";
    }

    /**
     * 修改
     */
    @Permission
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Visitor visitor) {
        visitorService.updateById(visitor);
        return SUCCESS_TIP;
    }

    /**
     * 刪除
     */
    @Permission
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer visitorId) {
        visitorService.deleteById(visitorId);
        return SUCCESS_TIP;
    }

    /**
     * excel 匯入
     */
    @RequestMapping(value = "/import", method= RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> importExcel(@RequestParam(value="file",required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> map = new HashMap<String, Object>();
        String result = visitorService.readExcelFile(file);
        map.put("message", result);
        return map;
    }

}

service

package com.stylefeng.guns.modular.server.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.modular.server.model.Visitor;
import com.baomidou.mybatisplus.service.IService;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;


/**
 * 訪客管理的服務類
 *
 * @author
 * @date 2018-09-27 17:30:19
 */
public interface IVisitorService extends IService<Visitor> {
    /**
     * 分頁查詢列表
     */
    List<Map<String,Object>> selectVisitorList(Page<Map<String, Object>> page, String visitorName, String orderByField, boolean asc);

        /**
         * 讀取excel中的資料,生成list
         */
        String readExcelFile(MultipartFile file);
}

serviceImp

package com.stylefeng.guns.modular.server.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.modular.server.dao.VisitorMapper;
import com.stylefeng.guns.modular.server.model.Visitor;
import com.stylefeng.guns.modular.server.service.IVisitorService;
import com.stylefeng.guns.modular.server.service.util.ReadExcel;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 訪客管理 的服務實現類
 *
 * @author
 * @date 2018-09-27 17:30:19
 */
@Service
public class VisitorServiceImpl extends ServiceImpl<VisitorMapper, Visitor> implements IVisitorService {

    @Override
    public List<Map<String, Object>> selectVisitorList(Page<Map<String, Object>> page, String visitorName, String orderByField, boolean asc) {
        return this.baseMapper.selectVisitorList(page, visitorName, orderByField, asc);
    }

    Visitor visitor = new Visitor();

    @Override
    public String readExcelFile(MultipartFile file) {
        String result = "";
        //建立處理EXCEL的類
        ReadExcel readExcel = new ReadExcel();
        //解析excel,獲取上傳的事件單
        List<Map<String, Object>> excelList = readExcel.getExcelInfo(file);
        //至此已經將excel中的資料轉換到list裡面了,接下來就可以操作list,可以進行儲存到資料庫,或者其他操作,
        for(Map<String, Object> row:excelList){
            visitor.setParkId(Integer.parseInt( row.get("parkId").toString() ));
            visitor.setVisitorName(row.get("visitorName").toString());
            visitor.setVisitorMobile(row.get("visitorMobile").toString());
            visitor.setCreatetime(new Date());
            visitor.setAppointTime(new Date());
            visitor.setFollowNum(1);
            visitor.setInviter("aaa");
            visitor.setInviterCompany("aaaaa");
            visitor.setVisitingTime(new Date());
            visitor.setStatus(1);
            boolean ret = insert(visitor);
            if(ret == false){
                result = "插入資料庫失敗";
            }
        }
        if(excelList != null && !excelList.isEmpty()){
            result = "上傳成功";
        }else{
            result = "上傳失敗";
        }
        return result;
    }

}

util

package com.stylefeng.guns.modular.server.service.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author
 *
 */
public class ReadExcel {
    // 總行數
    private int totalRows = 0;
    // 總條數
    private int totalCells = 0;
    // 錯誤資訊接收器
    private String errorMsg;

    // 構造方法
    public ReadExcel() {
    }

    // 獲取總行數
    public int getTotalRows() {
        return totalRows;
    }

    // 獲取總列數
    public int getTotalCells() {
        return totalCells;
    }

    // 獲取錯誤資訊
    public String getErrorInfo() {
        return errorMsg;
    }

    /**
     * 讀EXCEL檔案,獲取資訊集合
     *
     * @param mFile
     * @return
     */
    public List<Map<String, Object>> getExcelInfo(MultipartFile mFile) {
        String fileName = mFile.getOriginalFilename();// 獲取檔名
//		List<Map<String, Object>> userList = new LinkedList<Map<String, Object>>();
        try {
            if (!validateExcel(fileName)) {// 驗證檔名是否合格
                return null;
            }
            boolean isExcel2003 = true;// 根據檔名判斷檔案是2003版本還是2007版本
            if (isExcel2007(fileName)) {
                isExcel2003 = false;
            }
            return createExcel(mFile.getInputStream(), isExcel2003);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根據excel裡面的內容讀取客戶資訊
     *
     * @param is      輸入流
     * @param isExcel2003   excel是2003還是2007版本
     * @return
     * @throws IOException
     */
    public List<Map<String, Object>> createExcel(InputStream is, boolean isExcel2003) {
        try {
            Workbook wb = null;
            if (isExcel2003) {// 當excel是2003時,建立excel2003
                wb = new HSSFWorkbook(is);
            } else {// 當excel是2007時,建立excel2007
                wb = new XSSFWorkbook(is);
            }
            return readExcelValue(wb);// 讀取Excel裡面客戶的資訊
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 讀取Excel裡面客戶的資訊
     *
     * @param wb
     * @return
     */
    private List<Map<String, Object>> readExcelValue(Workbook wb) {
        // 得到第一個shell
        Sheet sheet = wb.getSheetAt(0);
        // 得到Excel的行數
        this.totalRows = sheet.getPhysicalNumberOfRows();
        // 得到Excel的列數(前提是有行數)
        if (totalRows > 1 && sheet.getRow(0) != null) {
            this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
        // 迴圈Excel行數
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            // 迴圈Excel的列
            Map<String, Object> map = new HashMap<String, Object>();
            for (int c = 0; c < this.totalCells; c++) {
                Cell cell = row.getCell(c);
                if (null != cell) {
                    if (c == 0) {
                        // 如果是純數字,比如你寫的是25,cell.getNumericCellValue()獲得是25.0,通過擷取字串去掉.0獲得25
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String parkId = String.valueOf(cell.getNumericCellValue());
                            map.put("parkId", parkId.substring(0, parkId.length() - 2 > 0 ? parkId.length() - 2 : 1));// 園區id
                        } else {
                            map.put("parkId", cell.getStringCellValue());//  園區id
                        }
                    } else if (c == 1) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String visitorName = String.valueOf(cell.getNumericCellValue());
                            map.put("visitorName",visitorName.substring(0, visitorName.length() - 2 > 0 ? visitorName.length() - 2 : 1));// 來訪姓名
                        } else {
                            map.put("visitorName",cell.getStringCellValue());// 來訪姓名
                        }
                    }else if (c == 2) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String visitorMobile = String.valueOf(cell.getNumericCellValue());
                            map.put("visitorMobile",visitorMobile.substring(0, visitorMobile.length() - 2 > 0 ? visitorMobile.length() - 2 : 1));// 訪客手機
                        } else {
                            map.put("visitorMobile",cell.getStringCellValue());// 訪客手機
                        }
                    }
                }
            }
            // 新增到list
            userList.add(map);
        }
        return userList;
    }

    /**
     * 驗證EXCEL檔案
     *
     * @param filePath
     * @return
     */
    public boolean validateExcel(String filePath) {
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
            errorMsg = "檔名不是excel格式";
            return false;
        }
        return true;
    }

    // @描述:是否是2003的excel,返回true是2003
    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    // @描述:是否是2007的excel,返回true是2007
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

}

maven新增配置

        <!--excel 匯入excel 需要的jar包 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>

參考網站 : https://blog.csdn.net/he140622hwt/article/details/78478960