CSV文件导出

 CSV导出工具类:

package com.eden.smarthome.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;



/**
 * @FileName CSVUtils.java
 * @Description:
 *
 * @Date 2018年10月23日 上午10:08:39
 * @author Eden
 * @version 1.0
 */
public class CSVUtils {

    /**
     * @Title: createCSVFile 
     * @Description:
     * @param exportData 源数据List
     * @param headerMap csv文件的列表头headerMap
     * @param outPutPath
     * @param fileName
     * @return 
     * @author Eden
     * @date 2018年10月23日 上午11:33:24
     */
    @SuppressWarnings("rawtypes")
    public static File createCSVFile(List exportData, LinkedHashMap headerMap, 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));
            // UTF-8使正确读取分隔符","
            csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"),
                    1024);
            // 写入文件头部
            for (Iterator propertyIterator = headerMap.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 = headerMap.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;
    }
    
    /** 
    * 下载csv文件 
    * 
    * @param path 
    * @param response 
    */ 
    public static void download(String path, HttpServletResponse response) {
        try {
            // path是指下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            filename = filename + ".csv";
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            toClient.write(buffer);
            // 处理乱码
            toClient.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * 删除该目录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;
                    }
                }
            }
        }
    }
    
}

调用实现代码:

//导出的目标数据
            List exportData = new ArrayList();
            Map<String, Object> row = null;
            for (int i = 0; i < deviceList.size(); i++) {
                row = new LinkedHashMap();
                row.put("1", deviceList.get(i).getLicense());
                row.put("2", deviceList.get(i).getSn());
                exportData.add(row);
            }
            //设置列头
            LinkedHashMap<String, String> headerMap = new LinkedHashMap<String, String>();
            headerMap.put("1", "license");
            headerMap.put("2", "SN");

            //生成CSV文件
            String fileName = taskId + "_"; // 定义文件名称
            File file = CSVUtils.createCSVFile(exportData, headerMap, CSV_TEMP_PATH, fileName);

            //下载CSV文件
            String path = CSV_TEMP_PATH.replace("//", "/");
            CSVUtils.download(path + "/" + file.getName(), response);

            //删除临时生成CSV文件
            CSVUtils.deleteFiles(CSV_TEMP_PATH);

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值