Java生成CSV文件实例详解
本文实例主要讲述了Java生成CSV文件的方法,具体实现步骤如下:
1、新建CSVUtils.java文件:
packagecom.saicfc.pmpf.internal.manage.utils; importjava.io.BufferedWriter; importjava.io.File; importjava.io.FileInputStream; importjava.io.FileNotFoundException; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.OutputStream; importjava.io.OutputStreamWriter; importjava.net.URLEncoder; importjava.util.ArrayList; importjava.util.Iterator; importjava.util.LinkedHashMap; importjava.util.List; importjava.util.Map; importjavax.servlet.http.HttpServletResponse; importorg.apache.commons.beanutils.BeanUtils; /** *文件操作 */ publicclassCSVUtils{ /** *生成为CVS文件 *@paramexportData *源数据List *@parammap *csv文件的列表头map *@paramoutPutPath *文件路径 *@paramfileName *文件名称 *@return */ @SuppressWarnings("rawtypes") publicstaticFilecreateCSVFile(ListexportData,LinkedHashMapmap,StringoutPutPath, StringfileName){ FilecsvFile=null; BufferedWritercsvFileOutputStream=null; try{ Filefile=newFile(outPutPath); if(!file.exists()){ file.mkdir(); } //定义文件名格式并创建 csvFile=File.createTempFile(fileName,".csv",newFile(outPutPath)); System.out.println("csvFile:"+csvFile); //UTF-8使正确读取分隔符"," csvFileOutputStream=newBufferedWriter(newOutputStreamWriter(newFileOutputStream( csvFile),"UTF-8"),1024); System.out.println("csvFileOutputStream:"+csvFileOutputStream); //写入文件头部 for(IteratorpropertyIterator=map.entrySet().iterator();propertyIterator.hasNext();){ java.util.Map.EntrypropertyEntry=(java.util.Map.Entry)propertyIterator.next(); csvFileOutputStream .write("""+(String)propertyEntry.getValue()!=null?(String)propertyEntry .getValue():""+"""); if(propertyIterator.hasNext()){ csvFileOutputStream.write(","); } } csvFileOutputStream.newLine(); //写入文件内容 for(Iteratoriterator=exportData.iterator();iterator.hasNext();){ Objectrow=(Object)iterator.next(); for(IteratorpropertyIterator=map.entrySet().iterator();propertyIterator .hasNext();){ java.util.Map.EntrypropertyEntry=(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(Exceptione){ e.printStackTrace(); }finally{ try{ csvFileOutputStream.close(); }catch(IOExceptione){ e.printStackTrace(); } } returncsvFile; } /** *下载文件 *@paramresponse *@paramcsvFilePath *文件路径 *@paramfileName *文件名称 *@throwsIOException */ publicstaticvoidexportFile(HttpServletResponseresponse,StringcsvFilePath,StringfileName) throwsIOException{ response.setContentType("application/csv;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName,"UTF-8")); InputStreamin=null; try{ in=newFileInputStream(csvFilePath); intlen=0; byte[]buffer=newbyte[1024]; response.setCharacterEncoding("UTF-8"); OutputStreamout=response.getOutputStream(); while((len=in.read(buffer))>0){ out.write(newbyte[]{(byte)0xEF,(byte)0xBB,(byte)0xBF}); out.write(buffer,0,len); } }catch(FileNotFoundExceptione){ System.out.println(e); }finally{ if(in!=null){ try{ in.close(); }catch(Exceptione){ thrownewRuntimeException(e); } } } } /** *删除该目录filePath下的所有文件 *@paramfilePath *文件目录路径 */ publicstaticvoiddeleteFiles(StringfilePath){ Filefile=newFile(filePath); if(file.exists()){ File[]files=file.listFiles(); for(inti=0;i<files.length;i++){ if(files[i].isFile()){ files[i].delete(); } } } } /** *删除单个文件 *@paramfilePath *文件目录路径 *@paramfileName *文件名称 */ publicstaticvoiddeleteFile(StringfilePath,StringfileName){ Filefile=newFile(filePath); if(file.exists()){ File[]files=file.listFiles(); for(inti=0;i<files.length;i++){ if(files[i].isFile()){ if(files[i].getName().equals(fileName)){ files[i].delete(); return; } } } } } /** *测试数据 *@paramargs */ @SuppressWarnings({"rawtypes","unchecked"}) publicstaticvoidmain(String[]args){ ListexportData=newArrayList<Map>(); Maprow1=newLinkedHashMap<String,String>(); row1.put("1","11"); row1.put("2","12"); row1.put("3","13"); row1.put("4","14"); exportData.add(row1); row1=newLinkedHashMap<String,String>(); row1.put("1","21"); row1.put("2","22"); row1.put("3","23"); row1.put("4","24"); exportData.add(row1); LinkedHashMapmap=newLinkedHashMap(); map.put("1","第一列"); map.put("2","第二列"); map.put("3","第三列"); map.put("4","第四列"); Stringpath="c:/export/"; StringfileName="文件导出"; Filefile=CSVUtils.createCSVFile(exportData,map,path,fileName); StringfileName2=file.getName(); System.out.println("文件名称:"+fileName2); } }
2、调用createCSVFile方法生成CSV文件
Stringname="银行退款数据"; ListexportData=newArrayList(); LinkedHashMapdatamMap=null; for(Iteratoriterator=refundList.iterator();iterator.hasNext();){ HashMapmap=(HashMap)iterator.next(); datamMap=newLinkedHashMap(); datamMap.put("1",map.get("merOrderId")); datamMap.put("2",DateUtil.convertDateToString("yyyyMMdd",(Date)map.get("orderTime"))); BigDecimalamount=(BigDecimal)map.get("amount"); StringamountString=amount.divide(newBigDecimal(10)).toPlainString(); datamMap.put("3",amountString); datamMap.put("4",map.get("remark")!=null?map.get("remark"):""); exportData.add(datamMap); } LinkedHashMapmap=newLinkedHashMap(); map.put("1","订单号"); map.put("2","支付日期"); map.put("3","退货现金金额(整数金额单位:分)"); map.put("4","退货原因"); Filefile=CSVUtils.createCSVFile(exportData,map,filePath,name);//生成CSV文件 fileName=file.getName(); CSVUtils.exportFile(response,filePath+fileName,fileName);//下载生成的CSV文件