Java编程之CSV文件导入与导出的实现

来源:互联网 发布:windows安装光盘下载 编辑:程序博客网 时间:2024/05/22 13:57

年前在开发功能模块的时候用到了CSV文件导入导出,就此整理一下,便于大家参考。

导入导出功能很多时候用到的都是Excel文件,但是现在越来越多的使用了CSV文件进行此操作,它是一个纯文本文件,可以用记事本打开,也可以用Excel打开。CSV文件不像Excel那样有很多条条框框,它使用硬回车分割每条记录,用逗号分隔每条数据的字段。

CSV格式的文件就是用硬回车和文本都好实现的表格,用Excel一读就成了表格。文件名后缀就是 .csv。

直接上代码吧!


导入部分

导入的时候基于Ajax请求,js代码如下:

[javascript] view plain copy
 print?
  1. function importIpMac(upload) {  
  2.     var importTextInfo = document.getElementById("importTextInfo");  
  3.     importTextInfo.value="";  
  4.     $.ajaxFileUpload({  
  5.         url: ctx + "/ipmac/importIpMac",  
  6.         type: 'post',  
  7.         secureuri: false,           // 一般设置为false  
  8.         fileElementId: 'upload',        // 上传文件的id、name属性名  
  9.         dataType: 'text',           // 返回值类型,一般设置为json、application/json  
  10.         success: function(data, status){  
  11.             getIpMacBase();  
  12.         },  
  13.         error: function(data, status, e){  
  14.             alert('请求异常!');  
  15.         }  
  16.     });  
  17. }  

Java代码控制层:

[java] view plain copy
 print?
  1. /** 
  2.  * 导入 
  3.  */  
  4. @ResponseBody  
  5. @RequestMapping(value = "/importIpMac", method = RequestMethod.POST, headers = { "content-type=multipart/form-data" })  
  6. public int importIpMac(HttpServletRequest request,  
  7.         HttpServletResponse response,  
  8.         @RequestParam(value = "upload") MultipartFile[] buildInfo)  
  9.         throws ServletException, IOException {  
  10.   
  11.     // 得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全  
  12.     String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");  
  13.     savePath = savePath.replace("file:"""); // 去掉file:  
  14.     File file1 = new File(savePath);  
  15.     // 判断上传文件的保存目录是否存在  
  16.     if (!file1.exists() && !file1.isDirectory()) {  
  17.         log.info(savePath + "目录不存在,需要创建");  
  18.         file1.mkdir();  
  19.     }  
  20.     // 删除此路径下的所有文件以及文件夹  
  21.     delAllFile(savePath);  
  22.   
  23.     try {  
  24.         InputStream is = buildInfo[0].getInputStream();// 多文件也适用,我这里就一个文件  
  25.         byte[] b = new byte[(int) buildInfo[0].getSize()];  
  26.         int read = 0;  
  27.         int i = 0;  
  28.         while ((read = is.read()) != -1) {  
  29.             b[i] = (byte) read;  
  30.             i++;  
  31.         }  
  32.         is.close();  
  33.         String filePath = savePath + "/" + "temp" + "_" + buildInfo[0].getOriginalFilename();  
  34.         log.info("临时文件保存路径:" + savePath + "/" + "temp" + "_" + buildInfo[0].getOriginalFilename());  
  35.         OutputStream os = new FileOutputStream(new File(savePath + "/" + "temp" + "_" + buildInfo[0].getOriginalFilename()));// 文件原名,如a.txt  
  36.         os.write(b);  
  37.         os.flush();  
  38.         os.close();  
  39.         topologyIpMacPortRealService.importIpMac(filePath);  
  40.     } catch (Exception e) {  
  41.         if (log.isDebugEnabled())  
  42.             log.debug("系统异常", e);  
  43.     }  
  44.   
  45.     return 1;  
  46. }  


Java代码实现层:

[java] view plain copy
 print?
  1. public int importIpMac(String filePath) throws Exception {  
  2.     // List<String> dataList=CSVUtils.importCsv(new File("/Users/wjm/Desktop/testexcel.csv"));  
  3.     List<String> dataList = CSVUtils.importCsv(new File(filePath));  
  4.     if (dataList != null && !dataList.isEmpty()) {  
  5.         for (int i = 1; i < dataList.size(); i++) {  
  6.             String data = dataList.get(i);  
  7.             SiTopologyIpMacPortBase base = new SiTopologyIpMacPortBase();  
  8.             String[] source = data.split(",");  
  9.             if (source[0] != "") {  
  10.                 base.setId(source[0]);  
  11.                 base.setMac(source[1]);  
  12.                 base.setIp(source[2]);  
  13.                 base.setUpIp(source[3]);  
  14.                 base.setUpName(source[4]);  
  15.                 base.setUpIndex(source[5]);  
  16.                 base.setModifyTime(source[6]);  
  17.   
  18.                 siTopologyIpMacPortBaseDao.insert(base);  
  19.             }  
  20.         }  
  21.     }  
  22.     return 1;  
  23. }  

其中CSVUtils类:

[java] view plain copy
 print?
  1. package com.one.si.toimpl.common.utils;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.BufferedWriter;  
  5. import java.io.File;  
  6. import java.io.FileOutputStream;  
  7. import java.io.FileReader;  
  8. import java.io.IOException;  
  9. import java.io.OutputStreamWriter;  
  10. import java.util.ArrayList;  
  11. import java.util.List;  
  12.   
  13. /**    
  14.  * CSV操作(导出和导入) 
  15.  * 
  16.  * @author wjm 
  17.  * @version 1.0 Nov 24, 2015 4:30:58 PM    
  18.  */  
  19. public class CSVUtils {  
  20.       
  21. <span style="white-space:pre">    </span>/** 
  22.      * 导出 
  23.      *  
  24.      * @param file csv文件(路径+文件名),csv文件不存在会自动创建 
  25.      * @param dataList 数据 
  26.      * @return 
  27.      */  
  28.     public static boolean exportCsv(File file, List<String> dataList){  
  29.         boolean isSucess=false;  
  30.           
  31.         FileOutputStream out=null;  
  32.         OutputStreamWriter osw=null;  
  33.         BufferedWriter bw=null;  
  34.         try {  
  35. //          OutputStreamWriter in_=new OutputStreamWriter(new FileOutputStream("文件名"), "gbk");  
  36.             out = new FileOutputStream(file);  
  37.             osw = new OutputStreamWriter(out, "gbk");  
  38.             bw =new BufferedWriter(osw);  
  39.             if(dataList!=null && !dataList.isEmpty()){  
  40.                 for(String data : dataList){  
  41.                     bw.append(data).append("\r");  
  42.                 }  
  43.             }  
  44.             isSucess=true;  
  45.         } catch (Exception e) {  
  46.             isSucess=false;  
  47.         }finally{  
  48.             if(bw!=null){  
  49.                 try {  
  50.                     bw.close();  
  51.                     bw=null;  
  52.                 } catch (IOException e) {  
  53.                     e.printStackTrace();  
  54.                 }   
  55.             }  
  56.             if(osw!=null){  
  57.                 try {  
  58.                     osw.close();  
  59.                     osw=null;  
  60.                 } catch (IOException e) {  
  61.                     e.printStackTrace();  
  62.                 }   
  63.             }  
  64.             if(out!=null){  
  65.                 try {  
  66.                     out.close();  
  67.                     out=null;  
  68.                 } catch (IOException e) {  
  69.                     e.printStackTrace();  
  70.                 }   
  71.             }  
  72.         }  
  73.           
  74.         return isSucess;  
  75.     }  
  76.       
  77.     /** 
  78.      * 导入 
  79.      *  
  80.      * @param file csv文件(路径+文件) 
  81.      * @return 
  82.      */  
  83.     public static List<String> importCsv(File file){  
  84.         List<String> dataList=new ArrayList<String>();  
  85.           
  86.         BufferedReader br=null;  
  87.         try {   
  88.             br = new BufferedReader(new FileReader(file));  
  89.             String line = "";   
  90.             while ((line = br.readLine()) != null) {   
  91.                 dataList.add(line);  
  92.             }  
  93.         }catch (Exception e) {  
  94.         }finally{  
  95.             if(br!=null){  
  96.                 try {  
  97.                     br.close();  
  98.                     br=null;  
  99.                 } catch (IOException e) {  
  100.                     e.printStackTrace();  
  101.                 }  
  102.             }  
  103.         }  
  104.    
  105.         return dataList;  
  106.     }  
  107. }  

导出部分

js部分:

[javascript] view plain copy
 print?
  1. /* 
  2.  * 导出基准表中的数据 
  3.  */  
  4. function exportIpMac() {  
  5.     window.open("exportIpMac.do");  
  6. }  

Java代码控制层:

[java] view plain copy
 print?
  1. /** 
  2.  * 导出的基准表信息 
  3.  */  
  4. @ResponseBody  
  5. @RequestMapping("/exportIpMac")  
  6. public String exportIpMac(HttpServletRequest request, HttpServletResponse response) throws Exception {  
  7.     List<String> dataList = topologyIpMacPortRealService.exportIpMac();  
  8.     response.setCharacterEncoding("GBK");  
  9.     SimpleDateFormat dfs = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式  
  10.     Date time = new Date();  
  11.     String tStamp = dfs.format(time);  
  12.     String filename = "IpMacPortExport"+tStamp + ".csv";  
  13.     response.setHeader("contentType""text/html; charset=GBK");  
  14.     response.setContentType("application/octet-stream");  
  15.     response.addHeader("Content-Disposition""attachment; filename="+filename);  
  16.     String cp=request.getSession().getServletContext().getRealPath("/");  
  17.     String path = cp+"download/"+filename;  
  18.     File file = new File(path);  
  19.     BufferedInputStream bis = null;  
  20.     BufferedOutputStream out = null;  
  21.     FileWriterWithEncoding fwwe =new FileWriterWithEncoding(file,"GBK");  
  22.     BufferedWriter bw = new BufferedWriter(fwwe);  
  23.     if(dataList!=null && !dataList.isEmpty()){  
  24.            for(String data : dataList){  
  25.                bw.write(data);  
  26.                bw.write("\n");  
  27.            }  
  28.        }  
  29.     bw.close();  
  30.     fwwe.close();  
  31.     try {  
  32.         bis = new BufferedInputStream(new FileInputStream(file));  
  33.         out = new BufferedOutputStream(response.getOutputStream());  
  34.         byte[] buff = new byte[2048];  
  35.         while (true) {  
  36.           int bytesRead;  
  37.           if (-1 == (bytesRead = bis.read(buff, 0, buff.length))){  
  38.               break;  
  39.           }  
  40.           out.write(buff, 0, bytesRead);  
  41.         }  
  42.         file.deleteOnExit();  
  43.     }  
  44.     catch (IOException e) {  
  45.         throw e;  
  46.     }  
  47.     finally{  
  48.         try {  
  49.             if(bis != null){  
  50.                 bis.close();  
  51.             }  
  52.             if(out != null){  
  53.                 out.flush();  
  54.                 out.close();  
  55.             }  
  56.         }  
  57.         catch (IOException e) {  
  58.             throw e;  
  59.         }  
  60.     }  
  61.     delAllFile(cp+"download/");  
  62.     return null;  
  63.   
  64. }  
Java代码实现层:

[java] view plain copy
 print?
  1. public List<String> exportIpMac() throws Exception {  
  2.     List<String> dataList = new ArrayList<String>();  
  3.     try {  
  4.         List<SiTopologyIpMacPortReal> list = siTopologyIpMacPortRealdao.selectAllData();  
  5.         dataList.add("ID,地址,IP地址,设备,设备名称,端口,更新时间");  
  6.         for (int i = 0; i < list.size(); i++) {  
  7.             dataList.add(list.get(i).getId() + "," + list.get(i).getMac()  
  8.                     + "," + list.get(i).getIp() + ","  
  9.                     + list.get(i).getUpIp() + ","  
  10.                     + list.get(i).getUpName() + ","  
  11.                     + list.get(i).getUpIfIndex() + ","  
  12.                     + list.get(i).getModifyTime());  
  13.         }  
  14.     } catch (Exception e) {  
  15.         e.printStackTrace();  
  16.     }  
  17.     return dataList;  
  18. }  


使用的是Chrome浏览器,下载的时候会直接在浏览器下面进行显示下载。
原创粉丝点击