欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现CSV文件导入与导出功能

程序员文章站 2023-10-30 18:46:34
年前在开发功能模块的时候用到了csv文件导入导出,就此整理一下,便于大家参考。 导入导出功能很多时候用到的都是excel文件,但是现在越来越多的使用了csv文件进行此操作...

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

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

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

直接上代码吧!

导入部分

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

function importipmac(upload) {
 var importtextinfo = 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" })
 public int importipmac(httpservletrequest request,
  httpservletresponse response,
  @requestparam(value = "upload") multipartfile[] buildinfo)
  throws servletexception, ioexception {
 
 // 得到上传文件的保存目录,将上传的文件存放于web-inf目录下,不允许外界直接访问,保证上传文件的安全
 string savepath = request.getsession().getservletcontext().getrealpath("/web-inf/upload");
 savepath = savepath.replace("file:", ""); // 去掉file:
 file file1 = new file(savepath);
 // 判断上传文件的保存目录是否存在
 if (!file1.exists() && !file1.isdirectory()) {
  log.info(savepath + "目录不存在,需要创建");
  file1.mkdir();
 }
 // 删除此路径下的所有文件以及文件夹
 delallfile(savepath);
 
 try {
  inputstream is = buildinfo[0].getinputstream();// 多文件也适用,我这里就一个文件
  byte[] b = new byte[(int) buildinfo[0].getsize()];
  int read = 0;
  int i = 0;
  while ((read = is.read()) != -1) {
  b[i] = (byte) read;
  i++;
  }
  is.close();
  string filepath = savepath + "/" + "temp" + "_" + buildinfo[0].getoriginalfilename();
  log.info("临时文件保存路径:" + savepath + "/" + "temp" + "_" + buildinfo[0].getoriginalfilename());
  outputstream os = new fileoutputstream(new file(savepath + "/" + "temp" + "_" + buildinfo[0].getoriginalfilename()));// 文件原名,如a.txt
  os.write(b);
  os.flush();
  os.close();
  topologyipmacportrealservice.importipmac(filepath);
 } catch (exception e) {
  if (log.isdebugenabled())
  log.debug("系统异常", e);
 }
 
 return 1;
 }

java代码实现层:

 public int importipmac(string filepath) throws exception {
 // list<string> datalist=csvutils.importcsv(new file("/users/wjm/desktop/testexcel.csv"));
 list<string> datalist = csvutils.importcsv(new file(filepath));
 if (datalist != null && !datalist.isempty()) {
  for (int i = 1; i < datalist.size(); i++) {
  string data = datalist.get(i);
  sitopologyipmacportbase base = new sitopologyipmacportbase();
  string[] source = data.split(",");
  if (source[0] != "") {
   base.setid(source[0]);
   base.setmac(source[1]);
   base.setip(source[2]);
   base.setupip(source[3]);
   base.setupname(source[4]);
   base.setupindex(source[5]);
   base.setmodifytime(source[6]);
 
   sitopologyipmacportbasedao.insert(base);
  }
  }
 }
 return 1;
 }

其中csvutils类:

package com.one.si.toimpl.common.utils;
 
import java.io.bufferedreader;
import java.io.bufferedwriter;
import java.io.file;
import java.io.fileoutputstream;
import java.io.filereader;
import java.io.ioexception;
import java.io.outputstreamwriter;
import java.util.arraylist;
import java.util.list;
 
/**  
 * csv操作(导出和导入)
 *
 * @author wjm
 * @version 1.0 nov 24, 2015 4:30:58 pm  
 */
public class csvutils {
 
<span style="white-space:pre"> </span>/**
   * 导出
   * 
   * @param file csv文件(路径+文件名),csv文件不存在会自动创建
   * @param datalist 数据
   * @return
   */
  public static boolean exportcsv(file file, list<string> datalist){
    boolean issucess=false;
    
    fileoutputstream out=null;
    outputstreamwriter osw=null;
    bufferedwriter bw=null;
    try {
//     outputstreamwriter in_=new outputstreamwriter(new fileoutputstream("文件名"), "gbk");
      out = new fileoutputstream(file);
      osw = new outputstreamwriter(out, "gbk");
      bw =new bufferedwriter(osw);
      if(datalist!=null && !datalist.isempty()){
        for(string data : datalist){
          bw.append(data).append("\r");
        }
      }
      issucess=true;
    } catch (exception e) {
      issucess=false;
    }finally{
      if(bw!=null){
        try {
          bw.close();
          bw=null;
        } catch (ioexception e) {
          e.printstacktrace();
        } 
      }
      if(osw!=null){
        try {
          osw.close();
          osw=null;
        } catch (ioexception e) {
          e.printstacktrace();
        } 
      }
      if(out!=null){
        try {
          out.close();
          out=null;
        } catch (ioexception e) {
          e.printstacktrace();
        } 
      }
    }
    
    return issucess;
  }
  
  /**
   * 导入
   * 
   * @param file csv文件(路径+文件)
   * @return
   */
  public static list<string> importcsv(file file){
    list<string> datalist=new arraylist<string>();
    
    bufferedreader br=null;
    try { 
      br = new bufferedreader(new filereader(file));
      string line = ""; 
      while ((line = br.readline()) != null) { 
        datalist.add(line);
      }
    }catch (exception e) {
    }finally{
      if(br!=null){
        try {
          br.close();
          br=null;
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
    }
 
    return datalist;
  }
}

导出部分

js部分:

/*
 * 导出基准表中的数据
 */
function exportipmac() {
 window.open("exportipmac.do");
}

java代码控制层:

 /**
 * 导出的基准表信息
 */
 @responsebody
 @requestmapping("/exportipmac")
 public string exportipmac(httpservletrequest request, httpservletresponse response) throws exception {
 list<string> datalist = topologyipmacportrealservice.exportipmac();
 response.setcharacterencoding("gbk");
 simpledateformat dfs = new simpledateformat("yyyymmddhhmmss");// 设置日期格式
 date time = new date();
 string tstamp = dfs.format(time);
 string filename = "ipmacportexport"+tstamp + ".csv";
 response.setheader("contenttype", "text/html; charset=gbk");
 response.setcontenttype("application/octet-stream");
 response.addheader("content-disposition", "attachment; filename="+filename);
 string cp=request.getsession().getservletcontext().getrealpath("/");
 string path = cp+"download/"+filename;
 file file = new file(path);
 bufferedinputstream bis = null;
 bufferedoutputstream out = null;
 filewriterwithencoding fwwe =new filewriterwithencoding(file,"gbk");
 bufferedwriter bw = new bufferedwriter(fwwe);
 if(datalist!=null && !datalist.isempty()){
      for(string data : datalist){
        bw.write(data);
        bw.write("\n");
      }
    }
 bw.close();
 fwwe.close();
 try {
  bis = new bufferedinputstream(new fileinputstream(file));
  out = new bufferedoutputstream(response.getoutputstream());
  byte[] buff = new byte[2048];
  while (true) {
   int bytesread;
   if (-1 == (bytesread = bis.read(buff, 0, buff.length))){
   break;
   }
   out.write(buff, 0, bytesread);
  }
  file.deleteonexit();
 }
 catch (ioexception e) {
  throw e;
 }
 finally{
  try {
  if(bis != null){
   bis.close();
  }
  if(out != null){
   out.flush();
   out.close();
  }
  }
  catch (ioexception e) {
  throw e;
  }
 }
 delallfile(cp+"download/");
 return null;
 
 }

java代码实现层:

public list<string> exportipmac() throws exception {
 list<string> datalist = new arraylist<string>();
 try {
  list<sitopologyipmacportreal> list = sitopologyipmacportrealdao.selectalldata();
  datalist.add("id,地址,ip地址,设备,设备名称,端口,更新时间");
  for (int i = 0; i < list.size(); i++) {
  datalist.add(list.get(i).getid() + "," + list.get(i).getmac()
   + "," + list.get(i).getip() + ","
   + list.get(i).getupip() + ","
   + list.get(i).getupname() + ","
   + list.get(i).getupifindex() + ","
   + list.get(i).getmodifytime());
  }
 } catch (exception e) {
  e.printstacktrace();
 }
 return datalist;
 }

使用的是chrome浏览器,下载的时候会直接在浏览器下面进行显示下载。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。