springMvc 中 Excel批量数据上传,利用POI解析数据保存入数据库 及模板文件下载

Jsp页面:

<div id="ss" style="padding:5px; width:410px; height:220px">
                    <form id="addequipForm" class="formee"  name="addequipForm" action="${pageContext.request.contextPath}/equip/save.do" method="post"  enctype="multipart/form-data">
					<table align="left">
						<tr><td style="height: 15px;"></td></tr>
						<tr>
							导入数据需先下载<a href="${pageContext.request.contextPath }/equip/download.do"><span style="color:red">【模板数据】</span></a>,并认真填写后再进行添加,</br>否则有可能导致添加失败!	
							<td>文件地址:</td>
							<td><input name="file" id="addequip" type="file" value="" /></td>
						</tr>
						<tr><td style="height: 10px;"></td></tr>
						<tr>
							<td colspan="1"><a href="javascript: void(0);" class="easyui-linkbutton" data-options="toggle:true,group:'g1'" οnclick="save();">添  加</a></td>
						</tr>
					</table>
			</form>
</div>


Js代码:


//修改
function save(){
		document.forms.addequipForm.submit( );	
}


Equipment实体类:


@Entity
@Table(name = "T_EQUIPMENT")
public class Equipment  extends UUIDEntity {	//uuid自动生成,可以不写
	private static final long serialVersionUID = 3283027241644822122L;
	@Column(name="CODE")
	private String code;	//设备编号
	@Column(name="TYPE")
	private String type;	//设备类型
	@Column(name="USERNAME")
	private String username;		//用户名字
	@Column(name="ADDRESS")
	private String address;		//用户住址
	@Column(name="DISDATE")
	private Date disDate;		//发放时间
	@Column(name="MEMO")
	private String memo;		//备注
//提供getter 和setter方法,快捷键alt+shift+ s 再按 r键 
//重写tostring方法,快捷键alt+shift+ s 再按 s键 
}
@MappedSuperclass
@AttributeOverride(name="id",column=@Column(name="id"))
public abstract class UUIDEntity extends IDEntity {
	
	@Id
	@Column(name="id")
	@GenericGenerator(name="genericID", strategy="uuid")
	@GeneratedValue(generator="genericID")
	private String id;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
}


Controller 层:


@RequestMapping("/save")
	public String savefile(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {
		String fileName = file.getOriginalFilename();		//原始文件名
		//System.out.println("原始文件名------->"+fileName);
		String uploadPath = PropertiesUtil.getProperty("xlsxUploadSavePath");	//这里可以写死一个本地磁盘路径: 如 d:/upload/xlsx等(具体到xlsx文件夹下面)

		System.out.println("配置文件uploadPath------>"+uploadPath);
	//	String ss = request.getSession().getServletContext().getRealPath(uploadPath);
		String newFileName = null;
		String newFilePath = null;
		if(!file.isEmpty()){  
             //加上分隔符号
			  String newDatePath =  File.separator+ DateUtil.getStringDateYMD()+ File.separator;	//加上分隔符号
			//  System.out.println("日期格式的文件夹------->"+newDatePath);
			  String savepath = uploadPath + newDatePath;
			 // System.out.println("保存路径------->"+savepath);
              String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
             // System.out.println("后缀名------->"+fileType);
              //如过是 2007 文件开始保存
              if(".xlsx".equals(fileType)){		
            	  newFileName = UIDServices.getUID().getUID()+ fileType;	//随机生产新文件名//这里是获得一个随机文件夹名称,可以不写,具体根据自己的需求
            	//  System.out.println("随机生产新文件名------->"+newFileName);
            	  File dirFile = new File(savepath);		//新建文件上传 到 的目的 文件夹
            	  
            	  if (!dirFile.exists()) {
            		  dirFile.mkdir();
            	  }
            	  File saveFile = new File(savepath+File.separator+newFileName);
            	  newFilePath = savepath+newFileName;
            	//  System.out.println("上传文件的地址------->"+newFilePath);
            	  try {  
            		  FileOutputStream os = new FileOutputStream(saveFile);  
            		  InputStream in = file.getInputStream();  
            		  int b=0;  
            		  while((b=in.read())!=-1){  
            			  os.write(b);  
            		  }  
            		  os.flush();  
            		  os.close();  
            		  in.close();  
            	  } catch (Exception e) { 
            		  e.printStackTrace();
            	  }
            	  
            	//------------开始解析----------------  
            	//------------开始解析----------------  
            	//------------开始解析----------------  
            	List<Equipment> tList = new ArrayList<Equipment>();		
            	  try {
					String filecopy = newFilePath;		//这里路径就是刚才咱们上传的文件位置
					XSSFWorkbook xssfWorkbook;
					xssfWorkbook = new XSSFWorkbook( filecopy);
					// 循环工作表Sheet
					for(int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++){
						XSSFSheet xssfSheet = xssfWorkbook.getSheetAt( numSheet);
						if(xssfSheet == null){
							continue;
						}
						
						// 循环行Row 
						for(int rowNum = 0; rowNum <= xssfSheet.getLastRowNum(); rowNum++ ){
							XSSFRow xssfRow = xssfSheet.getRow( rowNum);
							if(xssfRow == null){
								continue;
							}
						}	
						// 循环列Cell   
						 for(int rowNum = 0; rowNum <= xssfSheet.getLastRowNum(); rowNum++ ){
						        XSSFRow xssfRow = xssfSheet.getRow( rowNum);
						        if(xssfRow == null){
						          continue;
						        }
						        
						         form = new Equipment();
						        // 循环列Cell   
						        for(int cellNum = 0; cellNum <= xssfRow.getLastCellNum(); cellNum++){
							          XSSFCell xssfCell = xssfRow.getCell( cellNum);
							          if(xssfCell == null ){		
							            continue;
							          }
							         
							          //   System.out.print("     "+getValue(xssfCell));
							          if(xssfCell.getCellType() == xssfCell.CELL_TYPE_BOOLEAN ){
							          	  boolean BooleanCellValue =  xssfCell.getBooleanCellValue();
							          }else if(xssfCell.getCellType() == xssfCell.CELL_TYPE_NUMERIC){
							        	  xssfCell.getNumericCellValue();
							          }else{
							        	    if(0== xssfCell.getColumnIndex()){
							        		  	String code = getValue(xssfCell);
								          		form.setCode(code);
							        	    }else if(1 == xssfCell.getColumnIndex()){  //getColumnIndex() 是列标 
								          	//	System.out.print("    第"+xssfCell.getRowIndex()+"行 第一列");
								          		String type = getValue(xssfCell);
								          		form.setType(type);
								          	}else if(2== xssfCell.getColumnIndex()){
								          		String address = getValue(xssfCell);
								          		form.setAddress(address);
								          	}else if(3== xssfCell.getColumnIndex()){
								          		String username = getValue(xssfCell);
								          		form.setUsername(username);
								          	}else if(4== xssfCell.getColumnIndex()){
								          		String date = getValue(xssfCell);
								          		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
								          		Date d;
												try {
													d = sdf.parse(date);
													form.setDisDate(d);
												} catch (ParseException e) {
													e.printStackTrace();
												}
								          		
								          	}else if(5== xssfCell.getColumnIndex()){
								          		String memo = getValue(xssfCell);
								          		form.setMemo(memo);
								          	}
							          }
						        }
						       System.out.print("from 对象的 值是:"+form.toString());
						       System.out.println("---第"+rowNum+"行---");
						        //批量保存数据库  
						        if(rowNum != 0 && rowNum != 1 && form.getCode() != null && !("".equals(form.getCode()))){			//去除表头 和 无效行
						        		tList.add(form);
						        }
						 	}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
            	System.out.println("上传表中的单表记录个数是:"+tList.size());
            	//执行保存数据库  
				equipmentService.addBatch(tList);	
              }else{
            	  //非 2007 文件(非.xlsx文件)
            	  
            	  return "redirect:/equip/list.do";
              }
		}
		
		return "redirect:/equip/list.do";
	}
// 获得不同类型的表格数据
	  @SuppressWarnings("static-access")
	  private String getValue(XSSFCell xssfCell){
			if(xssfCell.getCellType() == xssfCell.CELL_TYPE_BOOLEAN){
			  return String.valueOf( xssfCell.getBooleanCellValue());
			}else if(xssfCell.getCellType() == xssfCell.CELL_TYPE_NUMERIC){
			  return String.valueOf( xssfCell.getNumericCellValue());
			}else{
			  return String.valueOf( xssfCell.getStringCellValue());
			}
	  }


附:

注:excel中所有的内容必须为文字字符:在excel的下发时间栏目表格内加一个英文的“”号,

上文中的form 是 Equipment 的具体实例。小心被误导.....

批量保存的源码:

@Transactional(propagation=Propagation.REQUIRED)
	public void addBatch(List<T> list) {
		for(T t:list){
			baseDao.add(t);
		}
}

baseDao中:

public void add(T entity) {
		getHibernateTemplate().save(entity);
}

DateUtil

public static String getStringDateYMD(){
		 SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
		 String newDate=format.format(new Date());
		return newDate;
}


文件下载:

jsp 页面:


<td id="downfile" colspan="3"><a href="${pageContext.request.contextPath }/equip/download.do" class="easyui-linkbutton"
 data-options="toggle:true,group:'g1'">点击下载</a></td> 

Controller


@RequestMapping("/download")  
    public void downloadFile(String fileName,HttpServletRequest  request,HttpServletResponse response){  
  		
  		response.setContentType("application/x-download; charset=utf-8");//1
        String xlsxDemoName = PropertiesUtil.getProperty("xlsxDemoName");		//这里是要下载的模板文件名,可以写死
        String xlsxUploadSavePath =  PropertiesUtil.getProperty("xlsxUploadSavePath");//这是要下载文件的路径,上线后就是另外的服务器地址,调试是本地磁盘,如d:/XXX
	//	String ss = request.getSession().getServletContext().getRealPath(uploadPath);
		try {
			if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {  
				xlsxDemoName = new String(xlsxDemoName.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器  
				response.setHeader("Content-disposition", "attachment; filename="+xlsxDemoName);
				xlsxDemoName = new String(xlsxDemoName.getBytes("ISO-8859-1"),"UTF-8");
	        } else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) { 
	        	response.setHeader("Content-disposition", "attachment; filename="+xlsxDemoName);
	        	xlsxDemoName = URLEncoder.encode(xlsxDemoName, "UTF-8");// IE浏览器
	        	xlsxDemoName = new String(xlsxDemoName.getBytes("ISO-8859-1"),"UTF-8");
	        }else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {  
	        	xlsxDemoName = new String(xlsxDemoName.getBytes("UTF-8"), "ISO8859-1");// 谷歌 
	        	response.setHeader("Content-disposition", "attachment; filename="+xlsxDemoName);
	        	xlsxDemoName = new String(xlsxDemoName.getBytes("ISO-8859-1"),"UTF-8");
	        }else{
	        	response.setHeader("Content-disposition", "attachment; filename="+URLEncoder.encode(xlsxDemoName,"utf-8"));
	        }
			
		//	response.setHeader("Content-disposition", "attachment; filename="+URLEncoder.encode(xlsxDemoName,"utf-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}         
  		
        try { 
            File file=new File(xlsxUploadSavePath+File.separator+xlsxDemoName);  
            InputStream inputStream=new FileInputStream(file);  
            OutputStream os=response.getOutputStream();  
            byte[] b=new byte[1024];  
            int length;  
            while((length=inputStream.read(b))>0){  
                os.write(b,0,length);  //os会自动关流
            }  
            inputStream.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
       
    } 

注:

访问浏览器的判断有点冗余:读者自行改善,我的这个项目,没法改,IE8就是不进它的循环里面,所有没办法,瞎写了,不过还是能正常下载.....

本人菜鸟一枚。有不正之处,希望大家指正交流,Q我:326082040thanks 












  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值