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

Java生成CSV文件实例详解

程序员文章站 2024-02-27 20:00:57
本文实例主要讲述了java生成csv文件的方法,具体实现步骤如下: 1、新建csvutils.java文件: package com.saicfc.pmpf.i...

本文实例主要讲述了java生成csv文件的方法,具体实现步骤如下:

1、新建csvutils.java文件:

package com.saicfc.pmpf.internal.manage.utils;

import java.io.bufferedwriter;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.io.outputstreamwriter;
import java.net.urlencoder;
import java.util.arraylist;
import java.util.iterator;
import java.util.linkedhashmap;
import java.util.list;
import java.util.map;

import javax.servlet.http.httpservletresponse;

import org.apache.commons.beanutils.beanutils;

/**
 * 文件操作
 */
public class csvutils {

  /**
   * 生成为cvs文件 
   * @param exportdata
   *       源数据list
   * @param map
   *       csv文件的列表头map
   * @param outputpath
   *       文件路径
   * @param filename
   *       文件名称
   * @return
   */
  @suppresswarnings("rawtypes")
  public static file createcsvfile(list exportdata, linkedhashmap map, string outputpath,
                   string filename) {
    file csvfile = null;
    bufferedwriter csvfileoutputstream = null;
    try {
      file file = new file(outputpath);
      if (!file.exists()) {
        file.mkdir();
      }
      //定义文件名格式并创建
      csvfile = file.createtempfile(filename, ".csv", new file(outputpath));
      system.out.println("csvfile:" + csvfile);
      // utf-8使正确读取分隔符"," 
      csvfileoutputstream = new bufferedwriter(new outputstreamwriter(new fileoutputstream(
        csvfile), "utf-8"), 1024);
      system.out.println("csvfileoutputstream:" + csvfileoutputstream);
      // 写入文件头部 
      for (iterator propertyiterator = map.entryset().iterator(); propertyiterator.hasnext();) {
        java.util.map.entry propertyentry = (java.util.map.entry) propertyiterator.next();
        csvfileoutputstream
          .write(""" + (string) propertyentry.getvalue() != null ? (string) propertyentry
            .getvalue() : "" + """);
        if (propertyiterator.hasnext()) {
          csvfileoutputstream.write(",");
        }
      }
      csvfileoutputstream.newline();
      // 写入文件内容 
      for (iterator iterator = exportdata.iterator(); iterator.hasnext();) {
        object row = (object) iterator.next();
        for (iterator propertyiterator = map.entryset().iterator(); propertyiterator
          .hasnext();) {
          java.util.map.entry propertyentry = (java.util.map.entry) propertyiterator
            .next();
          csvfileoutputstream.write((string) beanutils.getproperty(row,
            (string) propertyentry.getkey()));
          if (propertyiterator.hasnext()) {
            csvfileoutputstream.write(",");
          }
        }
        if (iterator.hasnext()) {
          csvfileoutputstream.newline();
        }
      }
      csvfileoutputstream.flush();
    } catch (exception e) {
      e.printstacktrace();
    } finally {
      try {
        csvfileoutputstream.close();
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
    return csvfile;
  }

  /**
   * 下载文件
   * @param response
   * @param csvfilepath
   *       文件路径
   * @param filename
   *       文件名称
   * @throws ioexception
   */
  public static void exportfile(httpservletresponse response, string csvfilepath, string filename)
                                                  throws ioexception {
    response.setcontenttype("application/csv;charset=utf-8");
    response.setheader("content-disposition",
      "attachment; filename=" + urlencoder.encode(filename, "utf-8"));

    inputstream in = null;
    try {
      in = new fileinputstream(csvfilepath);
      int len = 0;
      byte[] buffer = new byte[1024];
      response.setcharacterencoding("utf-8");
      outputstream out = response.getoutputstream();
      while ((len = in.read(buffer)) > 0) {
        out.write(new byte[] { (byte) 0xef, (byte) 0xbb, (byte) 0xbf });
        out.write(buffer, 0, len);
      }
    } catch (filenotfoundexception e) {
      system.out.println(e);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (exception e) {
          throw new runtimeexception(e);
        }
      }
    }
  }

  /**
   * 删除该目录filepath下的所有文件
   * @param filepath
   *      文件目录路径
   */
  public static void deletefiles(string filepath) {
    file file = new file(filepath);
    if (file.exists()) {
      file[] files = file.listfiles();
      for (int i = 0; i < files.length; i++) {
        if (files[i].isfile()) {
          files[i].delete();
        }
      }
    }
  }

  /**
   * 删除单个文件
   * @param filepath
   *     文件目录路径
   * @param filename
   *     文件名称
   */
  public static void deletefile(string filepath, string filename) {
    file file = new file(filepath);
    if (file.exists()) {
      file[] files = file.listfiles();
      for (int i = 0; i < files.length; i++) {
        if (files[i].isfile()) {
          if (files[i].getname().equals(filename)) {
            files[i].delete();
            return;
          }
        }
      }
    }
  }

  /**
   * 测试数据
   * @param args
   */
  @suppresswarnings({ "rawtypes", "unchecked" })
  public static void main(string[] args) {
    list exportdata = new arraylist<map>();
    map row1 = new linkedhashmap<string, string>();
    row1.put("1", "11");
    row1.put("2", "12");
    row1.put("3", "13");
    row1.put("4", "14");
    exportdata.add(row1);
    row1 = new linkedhashmap<string, string>();
    row1.put("1", "21");
    row1.put("2", "22");
    row1.put("3", "23");
    row1.put("4", "24");
    exportdata.add(row1);
    linkedhashmap map = new linkedhashmap();
    map.put("1", "第一列");
    map.put("2", "第二列");
    map.put("3", "第三列");
    map.put("4", "第四列");

    string path = "c:/export/";
    string filename = "文件导出";
    file file = csvutils.createcsvfile(exportdata, map, path, filename);
    string filename2 = file.getname();
    system.out.println("文件名称:" + filename2);
  }
}

2、调用createcsvfile方法生成csv文件

string name = "银行退款数据";
list exportdata = new arraylist();
linkedhashmap datammap = null;
for (iterator iterator = refundlist.iterator(); iterator.hasnext();) {
   hashmap map = (hashmap) iterator.next();
   datammap = new linkedhashmap();
   datammap.put("1", map.get("merorderid"));
   datammap.put("2",dateutil.convertdatetostring("yyyymmdd", (date) map.get("ordertime")));
   bigdecimal amount = (bigdecimal) map.get("amount");
   string amountstring = amount.divide(new bigdecimal(10)).toplainstring();
   datammap.put("3", amountstring);
   datammap.put("4", map.get("remark") != null ? map.get("remark") : "");
   exportdata.add(datammap);
}
 linkedhashmap map = new linkedhashmap();
 map.put("1", "订单号");
 map.put("2", "支付日期");
 map.put("3", "退货现金金额(整数金额 单位:分)");
 map.put("4", "退货原因");
 file file = csvutils.createcsvfile(exportdata, map, filepath, name);//生成csv文件
 filename = file.getname();
 csvutils.exportfile(response, filepath + filename, filename);//下载生成的csv文件