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

实现前端一键后台生成csv文件以及csv下载功能

程序员文章站 2022-04-03 19:13:23
...
后台生成csv文件,完成前端下载功能

后台java代码
package com.jzt.mdsl.core.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
* @throws IOException
   */
  @SuppressWarnings("rawtypes")
  public static void createCSVFile(HttpServletResponse response,List exportData, LinkedHashMap map, String outPutPath,
                   String fileName) throws IOException {
    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));
      // UTF-8使正确读取分隔符","
      csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
        csvFile), "UTF-8"), 1024);
      // 写入文件头部
      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();
          if((String) BeanUtils.getProperty(row,(String) propertyEntry.getKey())!=null){
              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();
      }
    }
   
    /*
     *
     */
    response.setContentType("application/csv;charset=UTF-8");
    response.setHeader("Content-Disposition",
      "attachment; filename=" + URLEncoder.encode(fileName+".csv", "UTF-8"));
    InputStream in = null;
    try {
      in = new FileInputStream(csvFile.getPath());
      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);
      }
      return ;
    } catch (FileNotFoundException e) {
      System.out.println(e);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    }
  }

  /**
   * 下载文件
   * @param response
   * @param csvFilePath
   *       文件路径
   * @param fileName
   *       文件名称
* @return
   * @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+".csv", "UTF-8"));
    File file = new File(csvFilePath);
    //判断文件是否存在
    if (file.exists()) {
      File[] files = file.listFiles();
      for (int i = 0; i < files.length; i++) {
        if (files[i].isFile()) {
          if (files[i].getName().indexOf(fileName)!=-1) {
    InputStream in = null;
    try {
      in = new FileInputStream(files[i].getPath());
      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);
      }
      return ;
    } 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().indexOf(fileName)!=-1) {
            files[i].delete();
            return;
          }
        }
      }
    }
  }

}

前端代码:
exportOrders : function() {
var createTimeStart=$("input[name='createTimeStart']").val();
var createTimeEnd=$("input[name='createTimeEnd']").val();
var ordCd=$("input[name='ordCd']").val();
var thirdpartCd=$("input[name='thirdpartCd']").val();
var finshTimeStart=$("input[name='finshTimeStart']").val();
var finshTimeEnd=$("input[name='finshTimeEnd']").val();
var courierName=$("input[name='courierName']").val();
var promCd=$("input[name='promCd']").val();
var orderTypes=$("select[name='orderTypes'] option:selected").text();
var pharmProv=$("select[name='pharmProv'] option:selected").text();
var pharmCity=$("select[name='pharmCity'] option:selected").text();
var pharmCounty=$("select[name='pharmCounty'] option:selected").text();
var pharmacy=$("input[name='pharmacy']").val();
var currStatus=$("select[name='currStatus'] option:selected").text();


pharmProv =window.encodeURI(window.encodeURI(pharmProv));
pharmCity =window.encodeURI(window.encodeURI(pharmCity));
pharmCounty =window.encodeURI(window.encodeURI(pharmCounty));

// alert(createTimeStart);
// alert(createTimeEnd);
// alert(ordCd);
// alert(thirdpartCd);
// alert(finshTimeStart);
// alert(finshTimeEnd);
// alert(courierName);
// alert(promCd);
// alert(orderTypes);
// alert(pharmProv);
// alert(pharmCity);
// alert(pharmCounty);
// alert(pharmacy);
// alert(currStatus);

var url="/logistic/modules/order/csvGenerate?createTimeStart="+createTimeStart+"&createTimeEnd="+createTimeEnd+
            "&ordCd="+ordCd+"&thirdpartCd="+thirdpartCd+"&finshTimeStart="+finshTimeStart+"&finshTimeEnd="+finshTimeEnd+"&courierName="+courierName+"&promCd="+promCd+
            "&orderTypes="+orderTypes+"&pharmProv="+pharmProv+"&pharmCity="+pharmCity+"&pharmCounty="+pharmCounty+"&pharmacy="+pharmacy+"&asdcurrStatus="+currStatus;
//location.href=url;
$("#csvDown").attr("href",url);
        $("#csvdowns").click();
//         $.ajax({
//             type:"GET",
//             url:"/logistic/modules/order/csvGenerate?createTimeStart="+createTimeStart+"&createTimeEnd="+createTimeEnd+
//             "&ordCd="+ordCd+"&thirdpartCd="+thirdpartCd+"&finshTimeStart="+finshTimeStart+"&finshTimeEnd="+finshTimeEnd+"&courierName="+courierName+"&promCd="+promCd+
//             "&orderTypes="+orderTypes+"&pharmProv="+pharmProv+"&pharmCity="+pharmCity+"&pharmCounty="+pharmCounty+"&pharmacy="+pharmacy+"&asdcurrStatus="+currStatus,
//             dataType:"json",     
//             contentType:"application/json",              
//             success:function(msg){
//             $("#csvdown").click();
//           $.ajax({
//                    type:"GET",
//                  url:"/logistic/modules/order/csvDelete",
//                     dataType:"json",     
//                    contentType:"application/json",              
//                    success:function(msg){
//                    
//                    }
//                });
//             }
//          });
},


注意统一编码格式,改方法唯一缺陷为,下载 文件后,使用wps打开会有部分中文乱码,是有office则没问题


写的有点乱,仅供学习参考,谢谢
相关标签: java cvs json