Java generated CSV file instance detailed

Source: Internet
Author: User

This article mainly describes the Java generated CSV file method, the implementation steps are as follows:

1. New Csvutils.java file:

 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;/*** File Operation*/ Public classCsvutils {/*** Born as a CVS file * *@paramexportdata Source Data list *@parammap CSV file list Header map *@paramoutPutPath File path *@paramfileName file name *@return     */@SuppressWarnings ("Rawtypes")     Public Staticfile Createcsvfile (List exportdata, Linkedhashmap Map, String outPutPath, String fileName) {file CSVFile=NULL; BufferedWriter Csvfileoutputstream=NULL; Try{File File=NewFile (OutPutPath); if(!file.exists ())            {File.mkdir (); }            //define the file name format and createCSVFile = File.createtempfile (FileName, ". csv",NewFile (OutPutPath)); System.out.println ("CSVFile:" +csvfile); //UTF-8 make the delimiter read correctly ","Csvfileoutputstream =NewBufferedWriter (NewOutputStreamWriter (NewFileOutputStream (CSVFile), "UTF-8"), 1024); System.out.println ("Csvfileoutputstream:" +Csvfileoutputstream); //write to file header             for(Iterator Propertyiterator =Map.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 (); //Write file Contents             for(Iterator Iterator =exportdata.iterator (); Iterator.hasnext ();) {Object row=(Object) iterator.next ();  for(Iterator Propertyiterator =Map.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 (); }        }        returnCSVFile; }    /*** Download File * *@paramResponse *@paramcsvfilepath File path *@paramfileName file name *@throwsIOException*/     Public Static voidExportfile (httpservletresponse response, String Csvfilepath, string fileName)throwsIOException {response.setcontenttype ("Application/csv;charset=utf-8"); Response.setheader ("Content-disposition", "attachment; Filename= "+Urlencoder.encode (FileName,"UTF-8")); InputStream in=NULL; Try{ in=NewFileInputStream (Csvfilepath); intLen = 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); }        } Catch(FileNotFoundException e) {System.out.println (e); } finally {            if(In! =NULL) {                Try{in.close (); } Catch(Exception e) {Throw NewRuntimeException (e); }            }        }    }    /*** Delete all files under the directory filepath * *@paramFilePath file directory path*/     Public Static voiddeletefiles (String filePath) {File file=NewFile (FilePath); if(File.exists ()) {file[] files=File.listfiles ();  for(inti = 0; i < files.length; i++) {                if(Files[i].isfile ()) {files[i].delete (); }            }        }    }    /*** Delete individual files * *@paramFilePath File directory path *@paramFileName File name*/     Public Static voidDeleteFile (String filePath, String fileName) {File file=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; }                }            }        }    }    /*** TEST Data * *@paramargs*/@SuppressWarnings ({"Rawtypes", "unchecked" })     Public Static voidMain (string[] args) {List ExportData=NewArraylist<map>(); Map Row1=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); Linkedhashmap Map=NewLinkedhashmap (); Map.put ("1", "first column"); Map.put ("2", "second column"); Map.put ("3", "third column"); Map.put ("4", "fourth column"); String Path= "c:/export/"; String FileName= "File Export"; File File=Csvutils.createcsvfile (exportdata, map, Path, fileName); String fileName2=File.getname (); System.out.println ("File name:" +fileName2); }}

2. Call the Createcsvfile method to generate the CSV file

String name = "Bank Refund Data"; List ExportData=NewArrayList (); Linkedhashmap Datammap=NULL;  for(Iterator Iterator =refundlist.iterator (); Iterator.hasnext ();) {HASHMAP Map=(HASHMAP) iterator.next (); Datammap=NewLinkedhashmap (); Datammap.put ("1", Map.get ("Merorderid")); Datammap.put ("2", Dateutil.convertdatetostring ("YyyyMMdd", (Date) map.get ("Ordertime"))); BigDecimal Amount= (BigDecimal) map.get ("Amount"); String amountstring= Amount.divide (NewBigDecimal (10) . toplainstring (); Datammap.put ("3", amountstring); Datammap.put ("4", Map.get ("remark")! =NULL? Map.get ("Remark"): "");        Exportdata.add (DATAMMAP); } linkedhashmap Map=NewLinkedhashmap (); Map.put ("1", "Order Number"); Map.put ("2", "Payment Date"); Map.put ("3", "Return cash amount (integer amount unit: minutes)"); Map.put ("4", "Reason for return"); File File= Csvutils.createcsvfile (ExportData, map, FilePath, name);//generate a CSV fileFileName =File.getname (); Csvutils.exportfile (response, FilePath+ filename, filename);//Download the generated CSV file

This article transferred from: http://www.jb51.net/article/52724.htm

Java generated CSV file instance detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.