This article mainly describes the Java generation of CSV file method, the implementation of the following steps:
1, new Csvutils.java file:
Package com.saicfc.pmpf.internal.manage.utils;
Import Java.io.BufferedWriter;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.io.OutputStreamWriter;
Import Java.net.URLEncoder;
Import java.util.ArrayList;
Import Java.util.Iterator;
Import Java.util.LinkedHashMap;
Import java.util.List;
Import Java.util.Map;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.commons.beanutils.BeanUtils;
/** * File operation/public class Csvutils {/** * born into a CVS file * @param exportdata * source data list * @param map * CSV file list header map * @param outputpath * File path * @param filename * file name * @return * * @Su
Ppresswarnings ("Rawtypes") public static File Createcsvfile (List exportdata, Linkedhashmap map, String OutputPath, String fileName) {File CSVFile = null;
BufferedWriter csvfileoutputstream = null;
try {File File = new file (OutputPath);
if (!file.exists ()) {File.mkdir ();
//define filename format and create csvfile = file.createtempfile (filename, ". csv", new file (OutputPath));
System.out.println ("CSVFile:" + csvfile); UTF-8 to read the delimiter correctly "," Csvfileoutputstream = new BufferedWriter (New OutputStreamWriter new FileOutputStream (c
Svfile), "UTF-8"), 1024);
System.out.println ("Csvfileoutputstream:" + csvfileoutputstream); Write 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 content 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 ();
} return csvfile;
/** * Download File * @param response * @param csvfilepath * File path * @param filename * file name * @throws ioexception/public Stati
c void Exportfile (httpservletresponse response, String Csvfilepath, String fileName)
Throws IOException {response.setcontenttype ("application/csv;charset=utf-8"); Response.setheader ("Content-disposition", "attachment;
Filename= "+ urlencoder.encode (fileName," UTF-8 "));
InputStream in = null;
try {in = new FileInputStream (Csvfilepath);
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);
The catch (FileNotFoundException e) {System.out.println (e); Finally {if (in!= null) {try {In.close();
catch (Exception e) {throw new RuntimeException (e); /** * Deletes all files under this directory FilePath * @param filePath * file directory path/public static void Delet
Efiles (String filePath) {File File = new file (FilePath);
if (file.exists ()) {file[] files = file.listfiles ();
for (int i = 0; i < files.length i++) {if (Files[i].isfile ()) {files[i].delete (); /** * Delete a single file * @param filePath * file directory path * @param filename * * * Name/Pub
Lic static void DeleteFile (String filePath, String fileName) {File File = new file (FilePath);
if (file.exists ()) {file[] files = file.listfiles (); for (int i = 0; i < files.length i++) {if (Files[i].isfile ()) {if (Files[i].getname (). Equals (Filen
AME)) {files[i].delete ();
Return
/** * Test data * @param args * * @SuppressWarnings ({"Rawtypes", "Unchecked"}) public static void main (string[] args) {List exportdata = new
Arraylist<map> ();
Map row1 = new linkedhashmap<string, string> ();
Row1.put ("1", "11");
Row1.put ("2", "12");
Row1.put ("3", "13");
Row1.put ("4", "14");
Exportdata.add (ROW1);
Row1 = new linkedhashmap<string, string> ();
Row1.put ("1", "21");
Row1.put ("2", "22");
Row1.put ("3", "23");
Row1.put ("4", "24");
Exportdata.add (ROW1);
Linkedhashmap map = new Linkedhashmap ();
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, calling the Createcsvfile method to generate a CSV file
String name = "Bank refund data";
List ExportData = new ArrayList ();
Linkedhashmap datammap = null; for (Iterator iterator = Refundlist.iterator (); Iterator.hasnext ();)
{HashMap map = (HASHMAP) iterator.next ();
Datammap = new Linkedhashmap ();
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 (new BigDecimal). Toplainstring ();
Datammap.put ("3", amountstring);
Datammap.put ("4", Map.get ("remark")!= null map.get ("remark"): "");
Exportdata.add (DATAMMAP);
} linkedhashmap map = new Linkedhashmap ();
Map.put ("1", "Order Number");
Map.put ("2", "Payment date");
Map.put ("3", "Return cash amount (in whole amount unit: cent)");
Map.put ("4", "Return Reason");
File File = Csvutils.createcsvfile (ExportData, map, FilePath, name);//generate CSV file filename = file.getname ();
Csvutils.exportfile (response, FilePath + filename, filename);//Download the generated CSV file