---
title: "导出Csv文件"
author: "1336224635"
date: "2014-08-08T09:07:46Z"
tags: []
categories: ["行业应用"]
slug: "csv"
draft: false
lastmod: "2014-08-08T09:44:55Z"
id: 2101578
url: "https://andy2019.iteye.com/blog/2101578"
---

导出Csv文件思路：1.首先把数据遍历，在服务器端生成Csv文件

                                2.将服务器端生成的Csv文件提供给客户端下载

注意：如果导出数据中有科学计数法表示：请在导出数据后加上“\\t”。

package com.neusoft.util.excel;

import java.io.BufferedWriter;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.OutputStream;  
import java.io.OutputStreamWriter;  
import java.net.URLEncoder;  
import java.util.Date;  
import java.util.Iterator;  
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.neusoft.common.exception.BaseException;  
import com.neusoft.dataCenter.residentManage.model.ResidentBean;

public class ExportCsv  
{

 private static final Logger logger = Logger.getLogger(ExportCsv.class);

 /\**  
  *  
  * 作用：获得Csv文件  
  *  
  * @param residentList  
  *            需要遍历的结合  
  * @param dirpath  
  *            临时文件路径  
  * @param Prefix  
  *            临时文件前缀  
  * @return  
  * @throws BaseException  
  \*/  
 public File getCsvFile(List&lt;ResidentBean&gt; residentList, String dirpath, String Prefix) throws BaseException  
 {  
  BufferedWriter out = null;  
  FileOutputStream writerStream = null;  
  int random = (int) (Math.random() * 1000 + 1);  
  File excelFile = null;  
  File dir = new File(dirpath);  
  if (!dir.exists())  
  {  
   dir.mkdirs();  
  }  
  try  
  {  
   File\[] filelist = dir.listFiles();  
   Date date = new Date();  
   for (int i = 0; i &lt; filelist.length; i++)  
   {  
    long modifytime = filelist\[i].lastModified();  
    long nowdate = date.getTime();

    if ((nowdate - modifytime) / 1000 &gt;= 3600)  
    {  
     filelist\[i].delete();  
    }

   }  
  } catch (Exception e)  
  {  
   logger.info("删除导出居民信息产生的临时文件异常", e);  
  }  
  try  
  {  
   excelFile = File.createTempFile(Prefix + random, ".csv", dir);  
   int i = 1;

   writerStream = new FileOutputStream(excelFile);  
   out = new BufferedWriter(new OutputStreamWriter(writerStream, "gb2312"));  
   out.write("序号,姓名,手机号码,街道名称,社区名称,小区名称,年龄,性别,民族,出生日期,身份证号码,政治面貌,文化程度,地址");// 换成你需要的表头  
   out.newLine();  
   Iterator&lt;ResidentBean&gt; resultIterator = residentList.iterator();  
   while (resultIterator.hasNext())  
   {  
    ResidentBean e = resultIterator.next();  
    StringBuffer tempBuffer = new StringBuffer();  
    tempBuffer.append(i);  
    tempBuffer.append(",");  
    tempBuffer.append(e.getName() == null ? "" : e.getName().trim());  
    tempBuffer.append(",");  
    tempBuffer.append(e.getMobile() == null ? "" : e.getMobile().trim() + "\\t");  
    tempBuffer.append(",");  
    tempBuffer.append(e.getStreetName() == null ? "" : e.getStreetName().trim());  
    tempBuffer.append(",");  
    tempBuffer.append(e.getCommunityName() == null ? "" : e.getCommunityName().trim().replace("\\r\\n", ""));  
    tempBuffer.append(",");  
    tempBuffer.append(e.getVillageName() == null ? "" : e.getVillageName().trim());  
    tempBuffer.append(",");  
    tempBuffer.append(e.getAge() == null ? "" : e.getAge().trim());  
    tempBuffer.append(",");  
    tempBuffer.append(e.getSex() == null ? "" : e.getSex().trim());  
    tempBuffer.append(",");  
    tempBuffer.append(e.getNation() == null ? "" : e.getNation().trim());  
    tempBuffer.append(",");  
    tempBuffer.append(e.getBirthday() == null ? "" : e.getBirthday().trim() + "\\t");  
    tempBuffer.append(",");  
    tempBuffer.append(e.getCardNo() == null ? "" : e.getCardNo().trim() + "\\t");  
    tempBuffer.append(",");  
    tempBuffer.append(e.getNationality() == null ? "" : e.getNationality().trim());  
    tempBuffer.append(",");  
    tempBuffer.append(e.getEdu() == null ? "" : e.getEdu().trim());  
    tempBuffer.append(",");  
    tempBuffer.append(e.getAddress() == null ? "" : e.getAddress().trim());  
    out.write(tempBuffer.toString());  
    out.newLine();  
    tempBuffer = null;  
    i++;  
   }  
   out.flush();  
  } catch (IOException e)  
  {  
   logger.error("生成居民信息CSV临时文件异常", e);  
  } finally  
  {  
   if (out != null)  
   {  
    try  
    {  
     out.close();  
    } catch (IOException e)  
    {  
     e.printStackTrace();  
    }  
   }  
   if (writerStream != null)  
   {  
    try  
    {  
     writerStream.close();  
    } catch (IOException e)  
    {  
     e.printStackTrace();  
    }  
   }  
  }  
  return excelFile;  
 }

 /\**  
  * 将服务器端生成的Excel文件提供给客户端下载  
  *  
  * @param response  
  * @param tempFile  
  \*/  
 public void download(HttpServletResponse response, File tempFile)  
 {  
  String filenamedownload = tempFile.toString();  
  String filenamedisplay = "居民信息.csv";

  OutputStream output = null;  
  FileInputStream fis = null;  
  try  
  {  
   filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");  
   response.addHeader("Content-Disposition", "attachment;filename=" + filenamedisplay);  
   output = response.getOutputStream();  
   fis = new FileInputStream(filenamedownload);

   byte\[] b = new byte\[1024];  
   int i = 0;  
   while ((i = fis.read(b)) &gt; 0)  
   {  
    output.write(b, 0, i);  
   }  
   output.flush();  
  } catch (Exception e)  
  {  
   // logger.error("导出居民信息CSV文件异常", e);  
  } finally  
  {  
   if (fis != null)  
   {  
    try  
    {  
     fis.close();  
    } catch (IOException e)  
    {  
     e.printStackTrace();  
    }  
    fis = null;  
   }  
   if (output != null)  
   {  
    try  
    {  
     output.close();  
    } catch (IOException e)  
    {  
     e.printStackTrace();  
    }  
    output = null;  
   }

  }  
 }

}

调用：

//residentList 需要导出的集合，一般是从数据库获得的数据

//exportDirPath 导出到服务器的Csv临时文件路径，一般是spring注入进来

//jumin 导出Csv临时文件前缀

ExportCsv xx = new ExportCsv();  
File tempfile = xx.getCsvFile(residentList, exportDirPath, "jumin");  
xx.download(response, tempfile);