java实现CSV文件导入与导出功能
年前在开发功能模块的时候用到了CSV文件导入导出,就此整理一下,便于大家参考。
导入导出功能很多时候用到的都是Excel文件,但是现在越来越多的使用了CSV文件进行此操作,它是一个纯文本文件,可以用记事本打开,也可以用Excel打开。CSV文件不像Excel那样有很多条条框框,它使用硬回车分割每条记录,用逗号分隔每条数据的字段。
CSV格式的文件就是用硬回车和文本都好实现的表格,用Excel一读就成了表格。文件名后缀就是.csv。
直接上代码吧!
导入部分
导入的时候基于Ajax请求,js代码如下:
functionimportIpMac(upload){ varimportTextInfo=document.getElementById("importTextInfo"); importTextInfo.value=""; $.ajaxFileUpload({ url:ctx+"/ipmac/importIpMac", type:'post', secureuri:false,//一般设置为false fileElementId:'upload',//上传文件的id、name属性名 dataType:'text',//返回值类型,一般设置为json、application/json success:function(data,status){ getIpMacBase(); }, error:function(data,status,e){ alert('请求异常!'); } }); }
Java代码控制层:
/** *导入 */ @ResponseBody @RequestMapping(value="/importIpMac",method=RequestMethod.POST,headers={"content-type=multipart/form-data"}) publicintimportIpMac(HttpServletRequestrequest, HttpServletResponseresponse, @RequestParam(value="upload")MultipartFile[]buildInfo) throwsServletException,IOException{ //得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全 StringsavePath=request.getSession().getServletContext().getRealPath("/WEB-INF/upload"); savePath=savePath.replace("file:","");//去掉file: Filefile1=newFile(savePath); //判断上传文件的保存目录是否存在 if(!file1.exists()&&!file1.isDirectory()){ log.info(savePath+"目录不存在,需要创建"); file1.mkdir(); } //删除此路径下的所有文件以及文件夹 delAllFile(savePath); try{ InputStreamis=buildInfo[0].getInputStream();//多文件也适用,我这里就一个文件 byte[]b=newbyte[(int)buildInfo[0].getSize()]; intread=0; inti=0; while((read=is.read())!=-1){ b[i]=(byte)read; i++; } is.close(); StringfilePath=savePath+"/"+"temp"+"_"+buildInfo[0].getOriginalFilename(); log.info("临时文件保存路径:"+savePath+"/"+"temp"+"_"+buildInfo[0].getOriginalFilename()); OutputStreamos=newFileOutputStream(newFile(savePath+"/"+"temp"+"_"+buildInfo[0].getOriginalFilename()));//文件原名,如a.txt os.write(b); os.flush(); os.close(); topologyIpMacPortRealService.importIpMac(filePath); }catch(Exceptione){ if(log.isDebugEnabled()) log.debug("系统异常",e); } return1; }
Java代码实现层:
publicintimportIpMac(StringfilePath)throwsException{ //ListdataList=CSVUtils.importCsv(newFile("/Users/wjm/Desktop/testexcel.csv")); List dataList=CSVUtils.importCsv(newFile(filePath)); if(dataList!=null&&!dataList.isEmpty()){ for(inti=1;i 其中CSVUtils类:
packagecom.one.si.toimpl.common.utils; importjava.io.BufferedReader; importjava.io.BufferedWriter; importjava.io.File; importjava.io.FileOutputStream; importjava.io.FileReader; importjava.io.IOException; importjava.io.OutputStreamWriter; importjava.util.ArrayList; importjava.util.List; /** *CSV操作(导出和导入) * *@authorwjm *@version1.0Nov24,20154:30:58PM */ publicclassCSVUtils{/** *导出 * *@paramfilecsv文件(路径+文件名),csv文件不存在会自动创建 *@paramdataList数据 *@return */ publicstaticbooleanexportCsv(Filefile,List dataList){ booleanisSucess=false; FileOutputStreamout=null; OutputStreamWriterosw=null; BufferedWriterbw=null; try{ //OutputStreamWriterin_=newOutputStreamWriter(newFileOutputStream("文件名"),"gbk"); out=newFileOutputStream(file); osw=newOutputStreamWriter(out,"gbk"); bw=newBufferedWriter(osw); if(dataList!=null&&!dataList.isEmpty()){ for(Stringdata:dataList){ bw.append(data).append("\r"); } } isSucess=true; }catch(Exceptione){ isSucess=false; }finally{ if(bw!=null){ try{ bw.close(); bw=null; }catch(IOExceptione){ e.printStackTrace(); } } if(osw!=null){ try{ osw.close(); osw=null; }catch(IOExceptione){ e.printStackTrace(); } } if(out!=null){ try{ out.close(); out=null; }catch(IOExceptione){ e.printStackTrace(); } } } returnisSucess; } /** *导入 * *@paramfilecsv文件(路径+文件) *@return */ publicstaticList importCsv(Filefile){ List dataList=newArrayList (); BufferedReaderbr=null; try{ br=newBufferedReader(newFileReader(file)); Stringline=""; while((line=br.readLine())!=null){ dataList.add(line); } }catch(Exceptione){ }finally{ if(br!=null){ try{ br.close(); br=null; }catch(IOExceptione){ e.printStackTrace(); } } } returndataList; } } 导出部分
js部分:
/* *导出基准表中的数据 */ functionexportIpMac(){ window.open("exportIpMac.do"); }Java代码控制层:
/** *导出的基准表信息 */ @ResponseBody @RequestMapping("/exportIpMac") publicStringexportIpMac(HttpServletRequestrequest,HttpServletResponseresponse)throwsException{ ListdataList=topologyIpMacPortRealService.exportIpMac(); response.setCharacterEncoding("GBK"); SimpleDateFormatdfs=newSimpleDateFormat("yyyyMMddHHmmss");//设置日期格式 Datetime=newDate(); StringtStamp=dfs.format(time); Stringfilename="IpMacPortExport"+tStamp+".csv"; response.setHeader("contentType","text/html;charset=GBK"); response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition","attachment;filename="+filename); Stringcp=request.getSession().getServletContext().getRealPath("/"); Stringpath=cp+"download/"+filename; Filefile=newFile(path); BufferedInputStreambis=null; BufferedOutputStreamout=null; FileWriterWithEncodingfwwe=newFileWriterWithEncoding(file,"GBK"); BufferedWriterbw=newBufferedWriter(fwwe); if(dataList!=null&&!dataList.isEmpty()){ for(Stringdata:dataList){ bw.write(data); bw.write("\n"); } } bw.close(); fwwe.close(); try{ bis=newBufferedInputStream(newFileInputStream(file)); out=newBufferedOutputStream(response.getOutputStream()); byte[]buff=newbyte[2048]; while(true){ intbytesRead; if(-1==(bytesRead=bis.read(buff,0,buff.length))){ break; } out.write(buff,0,bytesRead); } file.deleteOnExit(); } catch(IOExceptione){ throwe; } finally{ try{ if(bis!=null){ bis.close(); } if(out!=null){ out.flush(); out.close(); } } catch(IOExceptione){ throwe; } } delAllFile(cp+"download/"); returnnull; } Java代码实现层:
publicListexportIpMac()throwsException{ List dataList=newArrayList (); try{ List list=siTopologyIpMacPortRealdao.selectAllData(); dataList.add("ID,地址,IP地址,设备,设备名称,端口,更新时间"); for(inti=0;i 使用的是Chrome浏览器,下载的时候会直接在浏览器下面进行显示下载。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。