文件下载公共方法 以及调用

/*
  * List<String[]>   传入
  * 公共方法
  */
 public static boolean exportCsv(File file, List dataList) {
  boolean isSuccess = false;
  
  if(file == null || !file.getName().toUpperCase().endsWith(格式)) {
   isSuccess = false;
  } else {
   FileOutputStream out = null;
   OutputStreamWriter osw = null;
   BufferedWriter bw = null;
   
   int i = 1;
   try {
    bw = new BufferedWriter(new FileWriter(file));
    for (int j = 0; j < dataList.size(); j++) {
     //第一行是标题
     String[] data = (String[])dataList.get(j);
     String dataStr = "";
     for (int k = 0; k < data.length; k++) {
      if(k == data.length - 1) {
       dataStr = dataStr + data[k];
      } else {
       dataStr = dataStr + data[k] + ",";
      }
     }
     bw.write(dataStr);
     bw.newLine();
    }
    bw.flush();
    isSuccess = true;
   } catch(IOException e) {
    e.printStackTrace();
    isSuccess = false;
   } finally {
    if(out != null) {
     try {
      out.close();
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
   }
   
  }
  
  return isSuccess;
 }

 

 

 

 

  调用

   File csvFile = null;
   try {
    //生成临时文件
    csvFile = File.createTempFile("模板名称", "模板格式");
   } catch (IOException e) {
    e.printStackTrace();
   }
   List<String[]> dataList = new ArrayList<String[]>();
   String[] data = new String[]{"姓名","年龄","编号"};  //文件列名称 
   dataList.add(data);
   
   CsvUtil.exportCsv(csvFile, dataList);

 

posted @ 2015-12-03 17:15  神玄晓  阅读(199)  评论(0编辑  收藏  举报