CVS文件生成下载

@Service
public class ReportExportUtil {

/**
 * 生成CVS文件
 *
 * @param dataset 源数据集合
 * @param map        csv文件的列表头map
 * @param fileName   文件名称
 * @return
 * @throws IOException
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 */
public static <T> void createCSVFile(Collection<T> dataset, LinkedHashMap map, String fileName,HttpServletResponse response)
        throws IOException, InvocationTargetException, NoSuchMethodException {
    BufferedWriter bufferedWriter = null;
    File csvFile = null;
    // 定义文件名格式并创建
    try {
        csvFile = File.createTempFile(fileName, ".csv");
        bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"),
                1024);
        // 写入头部
        for (Iterator headIterator = map.entrySet().iterator(); headIterator.hasNext(); ) {
            Map.Entry headEntry = (Map.Entry) headIterator.next();
            bufferedWriter.write((String) headEntry.getValue() != null ? (String) headEntry.getValue() : "");
            if (headIterator.hasNext()) {
                bufferedWriter.write(",");
            }
        }
        bufferedWriter.newLine();
        Iterator<T> it = dataset.iterator();
        while (it.hasNext()) {
            T t = (T) it.next();
            // 获取类属性
            Field[] fields = t.getClass().getDeclaredFields();
            String[] csvContent = new String[fields.length];
            for (short i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String fieldName = field.getName();
                String fieldType = field.getType().toString();
                if ( !isContains(fieldName)&&i == fields.length - 1) {
                    bufferedWriter.newLine();
                }
                if (!isContains(fieldName)) {
                    continue;
                }

                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                try {
                    Class tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName, new Class[]{});
                    Object value = getMethod.invoke(t, new Object[]{});
                    // 取值并赋给数组
                    String textvalue = null;
                    if (value==null){
                        textvalue = " ";
                    }else{
                        if (fieldType.equals("class java.util.Date")) {
                            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                            textvalue = sdf.format(value);
                        }else{
                            textvalue = value.toString();
                        }
                    }
                    bufferedWriter.write(textvalue);
                    if (i < fields.length - 1) {
                        bufferedWriter.write(",");
                    }
                    if (i == fields.length - 1) {
                        bufferedWriter.newLine();
                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
            bufferedWriter.flush();
        }
    } finally {
        bufferedWriter.close();
    }

    byte[] b = new byte[1024];
    File fileLoad = new File(csvFile.getCanonicalPath());
    response.reset();
    response.setContentType("application/csv");
    String trueCSVName="PaymentReport_" + DateUtils.getCurrentDateTime() + ".csv";
    trueCSVName = new String(trueCSVName.getBytes("GBK"), "ISO8859-1");
    response.setHeader("Content-Disposition", "attachment; filename=" + trueCSVName);
    FileInputStream in = new FileInputStream(fileLoad);
    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);
    }
    in.close();
    csvFile.delete();

}

/**
 * 下载文件
 *
 * @param response
 * @param csvFilePath 文件路径
 * @param fileName    文件名称
 */
public static void exportFile(HttpServletResponse response, String csvFilePath, String fileName) {
    response.setContentType("application/csv;charset=UTF-8");
    InputStream in = null;
    try {
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        in = new FileInputStream(csvFilePath+fileName);
        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);
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException();
            }
        }
    }
}


public static LinkedHashMap<String,String> getreportHeaders(){
    LinkedHashMap map = new LinkedHashMap();
    map.put("1", "日期");
    map.put("2", "通证编号");
    map.put("3", "签发日期");
    map.put("4", "持证方");
    map.put("5", "到期悦票金额");
    return map;
}

/**
 * 判断是否是报表字段
 * @param field
 * @return
 */
public static boolean isContains(String field){
    Set reportFields = new HashSet(Arrays.asList("expireDate", "tokenNo","issueDate","toCorpName","amount"));
    if (reportFields.contains(field)) {
        return true;
    }else{
        return false;
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值