poi批量实现导入功能,jxl实现导入预览功能

////////////总结:
		导入流程:先下载导入模板,根据导入模板填写内容,填写完保存到本地,
		点击批量数据导入弹出导入文件选择界面,点击预览数据弹出表格,
		点击导入数据,开始导入。
		其中技术点有:io实现下载,poi实现导入,jxl实现导入预览。
		需要的jar:
		poi-3.14-20160307.jar
		poi-extend4.0-20150421.jar
		jxl.jar
		commons-fileupload-1.3.1.jar
		commons-io-2.4.jar
<a href="javascript:void(0)" class="easyui-linkbutton" id="docpath" iconCls="icon-excel" plain="true" onclick="DownLoad()">批量数据导入模版</a>
	  
点击批量数据导入模版的时候执行
function DownLoad(){
		$('#fpForm').submit();
}

//这个是对应的下载导入模板
<div id="fpForm1" style="float:left;margin-left:25px;">
	<form id="fpForm" action="${request.contextPath}/TdLawTask/download"  method="post"><!--action对应的是controle路径-->
		<label style="width:60px"></label><input id="fp" name="filepath" value="WEB-INF/upload/files/import/单位导入数据模板.xls" type="hidden"  /><!--value是模板路径值-->
	</form>
</div>

提交到后台controle的路径(action="${request.contextPath}/TdLawTask/download")
/**
 * @Description下载选中行的附件
 */
@ResponseBody
@RequestMapping("download")
public void download(@RequestParam String filepath,
		HttpServletRequest request, HttpServletResponse response) {
	filepath = filepath.replace("/", "\\");
	FileUtil.downloadfile(filepath, request, response);
}
	
下载工具类FileUtil
/**
 * 下载文件(不需要修改,直接使用)
 * 
 * @param file
 * @param request
 * @param isPic
 * @return
 */
public static String downloadfile(String filepath,
		HttpServletRequest request, HttpServletResponse response) {
	String filename = "";
	//windows 中和liunx中路径格式不一致
	if (File.separator.equals("\\")) {
		filepath = filepath.replace("/", "\\");
		filename = filepath.substring(filepath.lastIndexOf("\\") + 1);
	} else {
		filepath = filepath.replace("\\", "/");
		filename = filepath.substring(filepath.lastIndexOf("/") + 1);
	}
	//设置响应编码格式
	response.setCharacterEncoding("utf-8");
	//设置文件ContentType类型,这样设置,会自动判断下载文件类型 
	response.setContentType("multipart/form-data");
	// response.setHeader("Content-Disposition", "attachment;fileName="
	// + filename);
	String path = "";
	try {
		//设置文件头:最后一个参数是设置下载文件名
		response.addHeader("Content-Disposition", "attachment;filename="
				+ new String(filename.getBytes("gbk"), "iso-8859-1")); // 转码之后下载的文件不会出现中文乱码
		//获取Web项目的全路径 
		path = request.getSession().getServletContext().getRealPath("/")
				+ filepath;
		File file = new File(path);
		if (!file.exists())
			return path;
		// System.out.println(path);
		response.addHeader("Content-Length", "" + file.length());
		InputStream inputStream = new FileInputStream(file);
		OutputStream os = response.getOutputStream();
		byte[] b = new byte[2048];
		int length;
		while ((length = inputStream.read(b)) > 0) {
			os.write(b, 0, length);
		}
		os.close();
		inputStream.close();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return path;
}


<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-excel" plain="true" onclick="implexll();">批量数据导入</a>

//点击批量数据导入时,打开批量导入数据表单
function implexll(){
	$('#dlgup').dialog('open').dialog('setTitle','导入excel');
	$('#impsearchfm').form('clear'); 
}

<!--批量导入数据表单-->
<div id="dlgup" class="easyui-dialog"  style="padding:10px 20px;" closed="true" buttons="#dlg-buttons-up">
	<form id="impsearchfm"  novalidate  method="post"  enctype="multipart/form-data" style="float:left">
			<div class="fitem">	
				<label style="width:90px">文件路径:</label>
				<input  name="file" id="file" class="easyui-filebox" style="width:240px" data-options="buttonText:'选择文件',buttonIcon:'icon-search',prompt:'文件路径...'" value="选择文件">
			</div>
	</form>
</div>
<div id="dlg-buttons-up">
	<a href="javascript:void(0)" onclick="preview();" class="easyui-linkbutton" iconCls="icon-search">预览数据</a>
	<a href="javascript:void(0)" onclick="implexl();" class="easyui-linkbutton" iconCls="icon-excel">导入数据</a>
</div>

<!--导入时预览表单-->
<div id="ppreview" class="easyui-dialog" closed="true" buttons="#dlg-buttons-up-ppreview" style="width:800px;height:500px;"  >
<table id="dgpreview"  class="easyui-datagrid"  style="width:auto;height:100%;overflow:hidden;"
	   striped="true" fit="true" fitColumns="true"  scrollbarSize=0
		pagination="false"  rownumbers="true" singleSelect="true"
	   data-options="fit:true,border:false,pagesize:2000,pageList:[20000]"  >   
  <thead>
	<tr>
		<th data-options="field:'userId',align:'left',halign:'center',width:'12%'">测试</th>
		<th data-options="field:'corpname',align:'left',halign:'center',width:'36%'" formatter=namecolor>测试1</th>
	</tr>
  </thead>
</table>
</div>
<div id="dlg-buttons-up-ppreview">
	<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#ppreview').dialog('close')" style="width:90px">取消</a>
</div>	

//点击预览数据
function preview(){
	$('#ppreview').dialog('open').dialog('setTitle','信息预览');
	
	var filename=$('#file').filebox('getValue');
			if(filename==null || filename=='')
			{
				showMsg('提示','请选择文件!');
				return;
			}
	$('#impsearchfm').form('submit',{
			url: '${request.contextPath}/business/getfilename',//请求后台
			onSubmit: function(){
			$.messager.progress({
				title : '提示',
				text : '数据处理中,请稍后....'
			   });
			   return true;
			},
			success: function(data){
			
			//上传文件并得到文件名
			loadPriview(data);
			}
	});
	
	function loadPriview(filename){
		$.ajax({
			type : 'get',
			url : '${request.contextPath}/business/preview',
			dataType : 'json',
			data : {data :filename},
			cache :false,
			success : function(data) {
				$.messager.progress('close');
				$('#dgpreview').datagrid({   
					data:data
				});			   
			}
		});
	}	
}
//${request.contextPath}/business/getfilename',//后台代码
/**
 * 
 * @Method_Name: getfilename
 * @Description: 上传文件并返回文件名
 */
@ResponseBody
@RequestMapping("getfilename")
public String getFileName(DicInputPrd dicinputprd,@RequestParam("file") MultipartFile file, HttpServletRequest request,HttpSession session) {
	String filePath="";
	String fileName="";
	
	if(file!=null){
		if(file.getSize()>0)
			filePath=FileUtil.upload(file, request, true);//调用下面的上传文件
		fileName=request.getSession().getServletContext()
				.getRealPath("/")+filePath;
	}
	return fileName;
}

上传下载工具类FileUtil
/**
 * 上传文件
 * 
 * @param file
 * @param request
 * @param isPic
 * @return
 */
public static String upload(MultipartFile file, HttpServletRequest request,
		Boolean isPic) {
	SimpleDateFormat dateformat = new SimpleDateFormat("yyyy_MM_dd/HHMMSS");
	//文件夹名字
	String pathDir = "upload" + File.separator + "imgs" + File.separator
			+ dateformat.format(new Date()) + (int) Math.random() * 1000
			+ File.separator;
	if (File.separator.equals("\\")) {
		pathDir = pathDir.replace("/", "\\");
	}

	if (isPic == false) {
		pathDir = pathDir.replace("imgs", "files");
	}

	String filename = file.getOriginalFilename();//获取文件名
	String extName = "";
	if (StrUtil.isNotBlank(filename)) {//判断是否为空,不为空走if
		int t = filename.lastIndexOf(".");
		if (t > 0) {
			extName = filename.substring(t).toLowerCase();//获取文件的后缀名字
		}
	}
	filename = sdf.format(new Date());//时间格式化
	// File file2 = new File(request.getSession().getServletContext()
	// .getRealPath(pathDir));
	pathDir += filename + extName;//上传的路径完整名
	String realPathDir = request.getSession().getServletContext()
			.getRealPath(pathDir);//项目的完整路径名
	// if(!file2.exists())
	// file2.mkdir();
	try {
		FileUtils.copyInputStreamToFile(file.getInputStream(), new File(
				realPathDir));
	} catch (IOException e) {
		e.printStackTrace();
	}
	return pathDir;
}
${request.contextPath}/business/preview',后台代码,获取excel表格中数据,并按照指定格式返回

//导入时预览
@ResponseBody
@RequestMapping("preview")
public JqueryUiJson preview(String data, HttpServletRequest request,HttpSession session) {	
	List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	try {
			InputStream is = new FileInputStream(data);    
			jxl.Workbook rwb = Workbook.getWorkbook(is);//得到工作薄
			Sheet[] rslist=rwb.getSheets();//工作薄(Workbook)中工作表(Sheet)对象数组 
			//循环读取sheet工作表
			for(int i=0;i<rslist.length;i++){
				//获取Sheet表中所包含的总行数:getRows()
				for(int j=1;j<rslist[i].getRows();j++){
					Map<String, Object> map = new HashMap<String,Object>();
					int length = rslist[i].getColumns();//获取Sheet表中所包含的总列数:getColumns()
					String[] content=new String[length];//内容数组content
					//如果一行没有任何内容,则跳过
					int flag = 0;
					for( int t=0;t<length;t++){//取到某行某列的内容
						content[t]=rslist[i].getCell(t,j).getContents().trim();
						if(!"".equals(content[t])&&content[t] != null){
							flag=1;
						}
					}
					if(flag==0){
						continue;
					}
					map.clear();
					
					//这里可以对某一列进行处理(这里可以修改start)
					String industry="";
					String [] stringArr = content[7].split(";");
					for(int t = 0;t<stringArr.length;t++){						
						String sql6 = "SELECT VALUE as industry FROM sys_aaaa WHERE id = 'dic' AND item = '"+stringArr[t]+"'";
						Map map6 = sqlMapper.selectOne(sql6,new Object[]{"industry"});
						if(map6!=null){
							industry += map6.get("industry").toString()+",";
						}
					}
					industry=industry.substring(0,industry.length()-1);
				   //这里可以对某一列进行处理(这里可以修改end)
					map.put("ceshi1", content[0]);
					map.put("ceshi2", content[1]);
					map.put("ceshi3", content[2]);
					map.put("ceshi4", content[3]);
					map.put("ceshi5", content[4]);
					map.put("ceshi6", content[5]);
					map.put("ceshi7", industry);
					map.put("ceshi8", content[6]);
					list.add(map);
				}
			}	
			rwb.close();//关闭工作薄
			//返回结果//返回(总条数(total),数据(rows))的格式。(这里根据自己需要的格式进行返回)
			JqueryUiJson jqueryUiJson = new JqueryUiJson(ExampleUtil.getPageInfo(list).getTotal(), list);
			return jqueryUiJson;
		}catch(Exception e){
				e.printStackTrace();
				return null;
		}	
	}
	
这个是分页数据格式化,包名:(import com.github.pagehelper.PageInfo)	
public static <T> PageInfo<T> getPageInfo(List<T> tlist) {
		PageInfo<T> pageinfo = new PageInfo<T>(tlist);
		return pageinfo;
	}


//点击导入数据
function implexl(){
	var filename=$('#file').filebox('getValue');//获取文件名
	if(filename==null || filename=='')
	{
		showMsg('提示','请选择文件!');
		return;
	}
	$('#impsearchfm').form('submit',{
			url: '${request.contextPath}/business/importExl',
			onSubmit: function(){
			$.messager.progress({//提示信息
				title : '提示',
				text : '数据处理中,请稍后....'
			   });
			   return true;
			},
			success: function(result){
			$.messager.progress('close');//成功关闭提示信息
			var rtnMsg="";
				if (result!="0"){
					showMsg('错误提示','上传数据不规范');
				} else {
					showMsg('提示','数据导入成功');
					//刷新列表 
					//关闭提示框
				}
			}
		});
} 

//导入时请求后台
'${request.contextPath}/business/importExl',请求对应的后台

/**
 * @Method_Name: importExl
 * @Description: 批量导入
 */
@ResponseBody
@RequestMapping("importExl")
public String importExl(@RequestParam("file") MultipartFile file, HttpServletRequest request,HttpSession session){
	try {
		String str = tdLawTaskService.importExl(file,session,type);
		return str;
	} catch (Exception e) {
		e.printStackTrace();
		return e.getMessage();
	}
}
service
public String importExl(MultipartFile file,HttpSession session,String type);

/**
 * @Method_Name: importExl
 * @Description: 导入
 */
public String importExl(MultipartFile file,HttpSession session,String type){
	String str = "";
	if(file!=null){
		ImportExcel impexc = new ImportExcel();
		//创建时间
		String createdate = DateTimeUtil.getDateTime();
		try {
			List<String> list = impexc.readExcelContent(file.getInputStream());//读取Excel数据内容
			String sql_head ="INSERT into td_law_sss (ceshi1,ceshi2,ceshi3)VALUES ";
			for (int i = 0; i < list.size(); i++) {
				String[] sourceStrArray = list.get(i).split(",",-1);   
			  //判断 空行 跳过
				if(StrUtil.konghang(sourceStrArray)){
					continue;
				}
				str =str+ "('"+sourceStrArray[0]+"'," +"'"+sourceStrArray[1]+"','"+sourceStrArray[2]+"'), ";
			}
			sqlMapper.insert(sql_head+str.substring(0, str.length()-2)+";");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return "0";
}

ImportExcel.java类Start
/**
 * 读取Excel数据内容
 * @param InputStream
 * @return Map 包含单元格数据内容的Map对象
 */
public List<String> readExcelContent(InputStream is) {
//  Map<Integer, String> content = new HashMap<Integer, String>();
	List<String> content = new ArrayList<String>();
	String str = "";
	try {
		fs = new POIFSFileSystem(is);
		wb = new HSSFWorkbook(fs);
	} catch (IOException e) {
		e.printStackTrace();
	}
	sheet = wb.getSheetAt(0);
	// 得到总行数
	int rowNum = sheet.getLastRowNum();
	row = sheet.getRow(0);
	//获取不为空的列个数
	int colNum = row.getPhysicalNumberOfCells();
	// 正文内容应该从第二行开始,第一行为表头的标题
	for (int i = 1; i <= rowNum; i++) {
		row = sheet.getRow(i);
	  //防止中间某行没有内容
		int flag = 0;
		if(null!=row){
			flag = 1;
		}
		if(flag == 0){
			continue;
		}
		int j = 0;
		while (j < colNum) {
			// 每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据
			// 也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean
			// str += getStringCellValue(row.getCell((short) j)).trim() +
			// "-";
			//得到Excel工作表指定行的单元格:row.getCell((short) j
			str += getCellFormatValue(row.getCell((short) j)).trim() + ","; //格式化数据
			j++;
		}
		content.add(str);
		str = "";
	}
	return content;
}

/**
 * 根据HSSFCell类型设置数据
 * @param cell
 * @return
 */
private String getCellFormatValue(HSSFCell cell) {
	String cellvalue = "";
	if (cell != null) {
		// 判断当前Cell(单元格)的Type
		switch (cell.getCellType()) {
		// 如果当前Cell的Type为NUMERIC
		case HSSFCell.CELL_TYPE_NUMERIC:
		case HSSFCell.CELL_TYPE_FORMULA: {
			// 判断当前的cell是否为Date
			if (HSSFDateUtil.isCellDateFormatted(cell)) {
				// 如果是Date类型则,转化为Data格式
				
				//方法1:这样子的data格式是带时分秒的:2011-10-12 0:00:00
				//cellvalue = cell.getDateCellValue().toLocaleString();
				
				//方法2:这样子的data格式是不带带时分秒的:2011-10-12
				Date date = cell.getDateCellValue();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				cellvalue = sdf.format(date);
				
			}
			// 如果是纯数字
			else {
				// 取得当前Cell的数值
				//cellvalue = String.valueOf(cell.getNumericCellValue());
				DecimalFormat df = new DecimalFormat("0");  
				cellvalue = df.format(cell.getNumericCellValue()); 
			}
			break;
		}
		// 如果当前Cell的Type为STRIN
		case HSSFCell.CELL_TYPE_STRING:
			// 取得当前的Cell字符串
			cellvalue = cell.getRichStringCellValue().getString();
			break;
		// 默认的Cell值
		default:
			cellvalue = " ";
		}
	} else {
		cellvalue = "";
	}
	return cellvalue;
}
ImportExcel.java类end

//StrUtil类中导入时判断空行
public static boolean konghang(String[] content){  
	int flag = 0;
	for( int t=0;t<content.length;t++){
		if(!"".equals(content[t])&&content[t] != null){
			flag=1;
			break;
		}
	}
	if(flag==0){
		return true;
	}
	return false;
}























猜你喜欢

转载自blog.csdn.net/wzm1994/article/details/78552084