天天看點

java excel導入_java 實作excel中的資料導入到資料庫表的功能(簡單版)

java excel導入_java 實作excel中的資料導入到資料庫表的功能(簡單版)

項目架構

1,背景:spring+springmvc+mybatis

2,前台: bootstrap+jquery+ajax

3,項目管理:maven

說明.excel處理函數需要引入poi的jar包,在pom.xml引入一下代碼

<!-- POI -->  
<dependency>  
    <groupId>org.apache.poi</groupId>  
    <artifactId>poi</artifactId>  
    <version>3.8</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.8</version>  
</dependency>  
           

别的架構大體上也是可以的,隻需稍微調整,如有問題,大家可留言讨論

實作的功能說明:将使用者資訊(姓名,性别,年齡)通過excel上傳,并儲存到資料庫

具體代碼如下

1,前台html代碼

<form enctype="multipart/form-data" id="batchUpload"  action="user/upload" 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"  οnclick="user.uploadBtn()" >上傳</button>  
           

前台頁面效果

excel内容展示

2,JS代碼

var User = 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 =  '/user/upload/';  
            var formData = new FormData($('form')[0]);  
            user.sendAjaxRequest(url,'POST',formData);  
        }  
    };  
    this.sendAjaxRequest = function(url,type,data){  
        $.ajax({  
            url : url,  
            type : type,  
            data : data,  
            success : function(result) {  
                alert( result);  
            },  
            error : function() {  
                alert( "excel上傳失敗");  
            },  
            cache : false,  
            contentType : false,  
            processData : false  
        });  
    };  
}  
var user;  
$(function(){  
    user = new User();  
    user.init();  
});  
3,domain層使用者的實體類


/**  
 * @author  liuchj  
 * @version 1.0    
 */  
public class User {  
    private  String name;  
    private String sex;  
    private String age;  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
this.name = name;  
    }  
    public String getSex() {  
        return sex;  
    }  
    public void setSex(String sex) {  
this.sex = sex;  
    }  
    public String getAge() {  
        return age;  
    }  
    public void setAge(String age) {  
        this.age = age;  
    }  
} 
           

4,controller層代碼

@Controller  
@RequestMapping("/user")  
public class UserController{  
    @Autowired  
    private UserService  userService;  
    @RequestMapping(value="/upload",method = RequestMethod.POST)  
    @ResponseBody  
    public String  upload(@RequestParam(value="file",required = false)MultipartFile file,HttpServletRequest request, HttpServletResponse response){  
        Sring result = userService.readExcelFile(file);  
        return result;  
    }  
}  
           

5,service層代碼

1),service層接口

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

2),service實作層代碼

@Service  
public class MeetingRoomServiceImpl implements MeetingRoomService {  
@Override  
    public String readExcelFile(MultipartFile file) {  
        String result ="";  
        //建立處理EXCEL的類  
        ReadExcel readExcel=new ReadExcel();  
        //解析excel,擷取上傳的事件單  
        List<User> useList = readExcel.getExcelInfo(file);  
        //至此已經将excel中的資料轉換到list裡面了,接下來就可以操作list,可以進行儲存到資料庫,或者其他操作,  
        //和你具體業務有關,這裡不做具體的示範  
        if(useList != null && !useList.isEmpty()){  
            result = "上傳成功";  
        }else{  
            result = "上傳失敗";  
        }  
        return result;  
    }  
} 
           

3),excel處理函數

/**  
 * @author liuchj
 * @version 1.0    
 */  
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 fielName 
   * @return 
   */  
    public List<User> getExcelInfo(MultipartFile mFile) {  
        String fileName = mFile.getOriginalFilename();//擷取檔案名  
        try {  
            if (!validateExcel(fileName)) {// 驗證檔案名是否合格  
                return null;  
            }  
            boolean isExcel2003 = true;// 根據檔案名判斷檔案是2003版本還是2007版本  
            if (isExcel2007(fileName)) {  
                isExcel2003 = false;  
            }  
            List<User> userList = createExcel(mFile.getInputStream(), isExcel2003);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return userList;  
    }  
  /** 
   * 根據excel裡面的内容讀取客戶資訊 
   * @param is 輸入流 
   * @param isExcel2003 excel是2003還是2007版本 
   * @return 
   * @throws IOException 
   */  
    public List<User> 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);  
            }  
            List<User> userList = readExcelValue(wb);// 讀取Excel裡面客戶的資訊  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return userList;  
    }  
  /** 
   * 讀取Excel裡面客戶的資訊 
   * @param wb 
   * @return 
   */  
    private List<User> 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<User> userList = new ArrayList<User>();  
        // 循環Excel行數  
        for (int r = 1; r < totalRows; r++) {  
            Row row = sheet.getRow(r);  
            if (row == null){  
                continue;  
            }  
            User user = new User();  
            // 循環Excel的列  
            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 name = String.valueOf(cell.getNumericCellValue());  
                            user.setName(name.substring(0, name.length()-2>0?name.length()-2:1));//名稱  
                        }else{  
                            user.setName(cell.getStringCellValue());//名稱  
                        }  
                    } else if (c == 1) {  
                        if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){  
                            String sex = String.valueOf(cell.getNumericCellValue());  
                            user.setSex(sex.substring(0, sex.length()-2>0?sex.length()-2:1));//性别  
                        }else{  
                            user.setSex(cell.getStringCellValue());//性别  
                        }  
                    } else if (c == 2){  
                        if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){  
                            String age = String.valueOf(cell.getNumericCellValue());  
                            user.setAge(age.substring(0, age.length()-2>0?age.length()-2:1));//年齡  
                        }else{  
                            user.setAge(cell.getStringCellValue());//年齡  
                        }  
                    }  
                }  
            }  
            // 添加到list  
            userList.add(user);  
        }  
        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)$");    
     }    
}
           

繼續閱讀