1 23 24 package org.dbforms.servlets; 25 26 import org.dbforms.servlets.reports.LineReportServletAbstract; 27 28 import java.io.OutputStream ; 29 import java.io.OutputStreamWriter ; 30 import java.io.PrintWriter ; 31 32 61 public class CSVReportServlet extends LineReportServletAbstract { 62 63 private static final char Q = '\"'; 64 65 private static final String DEFAULTMIMETYPE = "text/comma-separated-values;charset=ASCII"; 66 67 private String clean(String s) { 68 s = s.replaceAll("\"", "\\\""); 69 return s; 70 } 71 72 protected String getMimeType() { 73 return DEFAULTMIMETYPE; 74 } 75 76 protected String getFileExtension() { 77 return ".csv"; 78 } 79 80 private PrintWriter pw; 81 82 protected void openStream(OutputStream out) throws Exception { 83 OutputStreamWriter osw; 84 try { 85 osw = new OutputStreamWriter (out, "UTF8"); 86 } catch (Exception e) { 87 osw = new OutputStreamWriter (out); 88 } 89 pw = new PrintWriter (osw); 90 } 91 92 protected void closeStream(OutputStream out) throws Exception { 93 pw.flush(); 94 pw.close(); 95 } 96 97 protected void writeData(Object [] data) throws Exception { 98 for (int i = 0; i < data.length; i++) { 99 if (i > 0) { 100 pw.print(','); 101 } 102 if (data[i] != null) { 103 pw.print(Q + clean(data[i].toString()) + Q); 104 } else { 105 pw.print(Q + "" + Q); 106 } 107 } 108 pw.println(); 109 } 110 111 } 112 | Popular Tags |