SSM项目的excel文件上传并添加到数据库

SSM项目的excel文件上传并添加到数据库(新手,不足之处请多多指教)

基于学校的课设,要用到excel文件的上传和数据库导入,在网上找了好多demo,最后找到一篇使用poi的,经过修改后,可以正常使用。特意写篇博客记录下来,以便日后使用。
说一下大体思路:

  1. 前台将excel文件传入到后台
  2. 使用excel工具类将excel文件中的数据读取成list集合
  3. 将list集合中的数据通过for-each取出,插入到数据库中。
  4. 返回信息到前台,插入成功。

首先是要用到的jar包(我这个项目使用的是Gradle)

    compile 'org.apache.poi:poi:3.17'
    compile 'org.apache.poi:poi-ooxml:3.17'
    compile 'org.apache.poi:poi-ooxml-schemas:3.17'
    compile 'org.apache.xmlbeans:xmlbeans:3.1.0'
    compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.1'
	compile group: 'commons-io', name: 'commons-io', version: '2.2'

Spring-MVC配置文件(差点忘了。。)

<bean id="multipartResolver"
	   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	   <property name="defaultEncoding" value="utf-8"></property>
	   <property name="maxUploadSize" value="10485760000"></property>
	   <property name="maxInMemorySize" value="40960"></property>
    </bean>

贴出代码
1.jsp代码(我这里使用的是easyui的filebox,也可以直接使用file输入框,使用正常的表单提交)

<div style="margin:50px;width:150px">
		<form id="form_excel" name="form_excel" method="post" enctype="multipart/form-data">
		  <tr>
		  <td>请选择Excel文件:</td>
		  <td>
			<input class="easyui-filebox" id="file_excel" style="width:200%" 
			buttonText="选择文件" accept="application/vnd.ms-excel" name="file_excel" />
		  </td>
		  </tr>
		  <tr>
		  <td colspan="2" align="right">
		      <a id="submit" href="#" class="easyui-linkbutton" 
		        data-options="iconCls:'icon-ok'">添加</a>
		  </td>
		  </tr>
		</form>
	</div>
	<script type="text/javascript">
	$(function(){
	    //登录表单提交 
	    $("#submit").click(function(){
	        $('#form_excel').form('submit', {
	            url:'${pageContext.request.contextPath}/manage/DoExcel',
	            onSubmit: function(){
	               
	            },
	            success:function(data){
	                if(data=="1"){
	                	alert("添加成功!");
	                    location.href="${pageContext.request.contextPath}/manage/main";
	                }else if(data=="2"){
                        alert("添加失败!");
                        location.href="${pageContext.request.contextPath}/manage/main";
                    }
	            }
	        });
	    })
	})
	</script>

2.Excel工具类(将Excel文件中数据转换为list集合)

package com.niqi.Utils;
import java.io.IOException;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
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;

import com.niqi.pojo.User;
/**
 * 读取excel文件中的数据
 * @author niqi
 *
 */
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();//获取文件名
		System.out.println("文件名"+fileName);
		List<User> stuList = null;
		try {
			if (!validateExcel(fileName)) {// 验证文件名是否合格
				return null;
			}
			boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
			if (isExcel2007(fileName)) {
				isExcel2003 = false;
			}
		  stuList = createExcel(mFile.getInputStream(), isExcel2003);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stuList;
	}
  /**
   * 根据excel里面的内容读取客户信息
   * @param is 输入流
   * @param isExcel2003 excel是2003还是2007版本
   * @return
   * @throws IOException
   */
	public List<User> createExcel(InputStream is, boolean isExcel2003) {
		List<User> stuList = null;
		try{
			Workbook wb = null;
			if (isExcel2003) {// 当excel是2003时,创建excel2003
				wb = new HSSFWorkbook(is);
			} else {// 当excel是2007时,创建excel2007
				wb = new XSSFWorkbook(is);
			}
			 stuList = readExcelValue(wb);// 读取Excel里面客户的信息
		} catch (IOException e) {
			e.printStackTrace();
		}
		return stuList;
	}  
  /**
   * 读取Excel里面客户的信息
   * @param wb
   * @return
   */
	private List<User> readExcelValue(Workbook wb) {
		// 得到第一个shell
		Sheet sheet = wb.getSheetAt(0);
		System.out.println("gaolei dayin============" +sheet);
		// 得到Excel的行数
		this.totalRows = sheet.getPhysicalNumberOfRows();
		System.out.println("行数======="+this.totalRows);
		// 得到Excel的列数(前提是有行数)
		if (totalRows > 1 && sheet.getRow(0) != null) {
			this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
			System.out.println("总列数=========="+this.totalCells);
		}
		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) {
//						if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
//							try {
//								user.setId(Integer.valueOf((int) cell.getNumericCellValue()));
//							} catch (NumberFormatException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//								System.out.println("if false");
//							}
//						}else{
//							try {
//								user.setId(Integer.valueOf(cell.getStringCellValue()));
//							} catch (Exception e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//								System.out.println("类型不匹配");
//							}
//						}
//					} else 
					    if (c == 1) {
						if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
						    //当导入数字大于8位时,会使用科学计数法,这里使用 BigDecimal
						    BigDecimal bd = new BigDecimal(cell.getNumericCellValue()); 
						    String accountid = bd.toPlainString();
							user.setAccountid(accountid);//账号
						}else{
                            user.setAccountid(cell.getStringCellValue());
                        }
					} 
					else if (c == 2){
						if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
							String password = String.valueOf(cell.getNumericCellValue());
							//如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
							String pwd =password.substring(0, password.length()-2>0?password.length()-2:1);
							user.setPassword(pwd);
						}else{
							user.setPassword(cell.getStringCellValue());
						}
					}
					else if (c == 3){  
						if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
							int sid = Integer.valueOf((int) cell.getNumericCellValue());
							user.setSid(sid);
						}else{
							user.setSid(Integer.valueOf((int) cell.getNumericCellValue()));
						}
					}
				}
			}
			// 添加到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)$");  
     }  
}

3.ServiceImpl(这里主要执行数据库插入操作)

package com.niqi.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.niqi.Utils.ReadExcel;
import com.niqi.dao.UserDao;
import com.niqi.pojo.User;
import com.niqi.service.HelpThreeDoExcelService;
/**
 * excel数据库插入业务实现层
 * @author niqi
 *
 */
@Service("helpThreeDoExcelService")
public class HelpThreeDoExcelServiceImpl implements HelpThreeDoExcelService {
	@Autowired
	private UserDao userdao; 
	@Override
	public String readExcelFile(MultipartFile file) {
		//创建处理EXCEL的类
        ReadExcel readExcel=new ReadExcel();
        //解析excel,获取上传的事件单
        List<User> userList = null;
        int insertResult = 0;
		String insertMsg = "";
		try {
			userList = readExcel.getExcelInfo(file);
			//至此已经将excel中的数据转换到list里面了,接下来就可以操作list,可以进行保存到数据库,或者其他操作,
			//和你具体业务有关,这里不做具体的示范
			//数据库插入		
			for(User s :userList) {
			    if(userdao.select(s)==null) {
				insertResult += userdao.insertSelective(s);
			    }
				System.out.println(s.toString());
			}
			if(insertResult ==0) {
				insertMsg = "All insert false";
			}else if(insertResult == userList.size()){
				insertMsg = "All insert success";
			}else {
				insertMsg = "Part insert success";
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("接受excel表格中的数据失败!!!");
		}
		for(User s : userList) {
        	System.out.println("打印excel中的数据"+s.toString());
        }
		return insertMsg;
	}
}

4.Controller层(与前台交互)

   //添加账号的方法  excel 相关的操作   能够将数据插入到数据库 
   @RequestMapping(value="DoExcel",method= {RequestMethod.POST})
   @ResponseBody
   public String DoExcel(@RequestParam(value="file_excel") MultipartFile file,HttpServletRequest request) {
       String readResult =null;
       try {
           readResult = helpThreeDoExcelService.readExcelFile(file);
           System.out.println("canshu :"+readResult);
       } catch (Exception e) {
           e.printStackTrace();
           System.out.println("upload failture");
       }
       if (readResult=="All insert false") {
           return "2";
       }
       System.out.println("插入结果="+readResult);
       return "1";
   }

5.UserMapper.xml(我也一并贴出来了,就是正常的插入语句)

<!-- 插入账号 -->
    <insert id="insertSelective" parameterType="com.niqi.pojo.User">
        insert into user(accountid,password,sid) values(#{accountid},#{password},#{sid}) 
    </insert>

最后贴一下运行图吧
Jsp页面
jsp页面
添加失败图(哈哈)
在这里插入图片描述
最后谢谢各位的阅读,祝各位早日(秃头)变强!!!

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值