//CSVUtil.class为类名
private static final Logger log = Logger.getLogger(CSVUtil.class);
//filepath 可以为本地路径,也可以为服务器路径
private static final String filepath = "C://Users//A//Downloads//";
public static voidmain(String[] args) {
List exportData= new ArrayList();
Map row1= new LinkedHashMap();
row1.put("11", "11");
row1.put("21", "12");
row1.put("31", "13");
row1.put("41", "14");
exportData.add(row1);
row1= new LinkedHashMap();
row1.put("11", "21");
row1.put("2", "22");
row1.put("31", "23");
row1.put("4", "24");
exportData.add(row1);
List propertyNames= newArrayList();
LinkedHashMap map= newLinkedHashMap();
map.put("11", "第一列");
map.put("22", "第二列");
map.put("33", "第三列");//System.out.println(map.keySet().toString().replace("[", "").replace("]", ""));
map.put("54", "第四列");
CSVUtil.createCSVFile(exportData, map,"C:\\Users\\A\\Downloads\\", "导出CSV文件");
}public staticFile createCSVFile(List exportData, LinkedHashMap rowMapper,
String outPutPath, String filename) {
File csvFile= null;
BufferedWriter csvFileOutputStream= null;try{
csvFile= new File(outPutPath + filename + ".csv");//csvFile.getParentFile().mkdir();
File parent =csvFile.getParentFile();if (parent != null && !parent.exists()) {
parent.mkdirs();
}
csvFile.createNewFile();//GB2312使正确读取分隔符","
csvFileOutputStream = new BufferedWriter(newOutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024);//写入文件头部
for (Iterator propertyIterator =rowMapper.entrySet().iterator(); propertyIterator.hasNext();) {
java.util.Map.Entry propertyEntry=(java.util.Map.Entry) propertyIterator
.next();
csvFileOutputStream.write("\""
+ propertyEntry.getValue().toString() + "\"");if(propertyIterator.hasNext()) {
csvFileOutputStream.write(",");
}
}
csvFileOutputStream.newLine();//写入文件内容
for (Iterator iterator =exportData.iterator(); iterator.hasNext();) {//Object row = (Object) iterator.next();
LinkedHashMap row =(LinkedHashMap) iterator.next();
System.out.println(row);for (Iterator propertyIterator =row.entrySet().iterator(); propertyIterator.hasNext();) {
java.util.Map.Entry propertyEntry=(java.util.Map.Entry) propertyIterator.next();//System.out.println( BeanUtils.getProperty(row, propertyEntry.getKey().toString()));
csvFileOutputStream.write("\""
+ propertyEntry.getValue().toString() + "\"");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();
}
}returncsvFile;
}
//导出到前端页面
public static String exportObeEventDataExcel(HttpServletResponse response,File csvFile){
try {
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(csvFile));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(
csvFile.getName(), "UTF-8"));
response.addHeader("Content-Length", "" + csvFile.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
return "成功";
} catch (IOException e) {
String message = "export ObeEvent Data Excel failed . ";
log.error(message, e);
return "失败";
}
}
//删除文件
if (csvFile.exists() && csvFile.isFile()){
csvFile.delete();
}
//上传文件,只返回文件名
public static String createCSVFileUrl(List>exportData,
String filename) {
log.info("开始生成csv文件");
File csvFile= null;
String PATH= "";
BufferedWriter csvFileOutputStream= null;try{
PATH= filepath + filename + ".csv";
csvFile= newFile(PATH);
File parent=csvFile.getParentFile();if (parent != null && !parent.exists()) {
parent.mkdirs();
}
csvFile.createNewFile();
log.info(PATH);//GB2312使正确读取分隔符","
csvFileOutputStream = new BufferedWriter(newOutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"), 1024);//写入文件头部
Map map1 = exportData.get(0);if (map1!=null && map1.size()>0) {int num =map1.keySet().size();int j = 0;for(String key : map1.keySet()) {//第六步,创建单元格,并设置值
csvFileOutputStream.write("\""
+ key.toString() + "\"");++j;if (j!=num) {
csvFileOutputStream.write(",");
}
}
}
csvFileOutputStream.newLine();//int i = 0 ;//写入文件内容
for (Iterator iterator =exportData.iterator(); iterator.hasNext();) {//Object row = (Object) iterator.next();
LinkedHashMap row =(LinkedHashMap) iterator.next();//i++;//System.out.println(row);//if (i%10000 == 0) {//System.out.println("正在写第"+i+"条数据!");//}
for (Iterator propertyIterator =row.entrySet().iterator(); propertyIterator.hasNext();) {
java.util.Map.Entry propertyEntry=(java.util.Map.Entry) propertyIterator.next();//System.out.println( BeanUtils.getProperty(row, propertyEntry.getKey().toString()));
csvFileOutputStream.write("\""
+ propertyEntry.getValue().toString() + "\"");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();
}
}
log.info("生成csv文件结束");//exportObeEventDataExcel(response,csvFile);//List list = new ArrayList();//list.add(filepath + filename + ".csv");//try {//zipFiles(list,filepath+"csv.zip",response);//} catch (IOException e) {// //TODO Auto-generated catch block//e.printStackTrace();//}//if (csvFile.exists() && csvFile.isFile())//{//csvFile.delete();//}
returnPATH;
}
/***@paramfileRealPathList 待压缩的文件列表
*@paramzipFileRealPath 压缩后的文件名称
*@returnboolean
*@throws:Exception
* @Function: zipFiles
* @Description:多个文件的ZIP压缩*/
public static void zipFiles(ListfileRealPathList, String zipFileRealPath,
HttpServletResponse response)throwsIOException
{
FileOutputStream out= null;
ZipOutputStream zipOut= null;
String path= filepath+zipFileRealPath+".zip";try{//根据文件路径构造一个文件实例
File zipFile = newFile(path);//判断目前文件是否存在,如果不存在,则新建一个
if (!zipFile.exists())
{
zipFile.createNewFile();
}//根据文件路径构造一个文件输出流
out = newFileOutputStream(path);//传入文件输出流对象,创建ZIP数据输出流对象
zipOut = newZipOutputStream(out);//循环待压缩的文件列表
for(String fileRealPath : fileRealPathList)
{
FileInputStream in= null;try{
File file= newFile(fileRealPath);if (!file.exists())
{
log.error("文件不存在");throw new FileNotFoundException("文件不存在");
}//创建文件输入流对象
in = newFileInputStream(fileRealPath);//得到当前文件的文件名称//判断操作系统
String separateCharacter = "";
String os= System.getProperty("os.name");if (os.toLowerCase().startsWith("win"))
{//windows操作系统
separateCharacter = "//";
}else{//非windows操作系统
separateCharacter = "/";
}
String fileName=fileRealPath.substring(
fileRealPath.lastIndexOf(separateCharacter)+ 1, fileRealPath.length());//创建指向压缩原始文件的入口
ZipEntry entry = newZipEntry(fileName);
zipOut.putNextEntry(entry);//向压缩文件中输出数据
int nNumber = 0;byte[] buffer = new byte[512];while ((nNumber = in.read(buffer)) != -1)
{
zipOut.write(buffer,0, nNumber);
}
}catch(IOException e)
{
log.error("文件压缩异常-in,原因:", e);throw new IOException("文件压缩异常");
}finally{//关闭创建的流对象
if (null !=in)
{
in.close();
}
}
}
}catch(IOException e)
{
log.error("文件压缩异常-out,原因:", e);throw new IOException("文件压缩异常");
}finally{if (null !=zipOut)
{
zipOut.close();
}if (null !=out)
{
out.close();
}
}
File fiel= newFile(path);//调用导出到前端的方法
exportObeEventDataExcel(response,fiel);//删除本地压缩包
if (fiel.exists() &&fiel.isFile())
{
fiel.delete();
}//删除其他文件
for(String string : fileRealPathList) {
File fiel1= newFile(string);//删除本地压缩包
if (fiel1.exists() &&fiel1.isFile())
{
fiel1.delete();
}
}
}
java 解析csv_java解析CSV文件(getCsvData 解析CSV文件 zipFiles 打成压缩包 exportObeEventDataExcel 前端页面响应)...