/** * Private constructor to prevent instantiation */ public CsvWriter(Table table, CsvWriteOptions options) { this.table = table; this.header = options.header(); this.writer = options.writer(); this.settings = new CsvWriterSettings(); // Sets the character sequence to write for the values that are null. settings.setNullValue(nullValue); settings.getFormat().setDelimiter(options.separator()); settings.getFormat().setQuote(options.quoteChar()); settings.getFormat().setQuoteEscape(options.escapeChar()); settings.getFormat().setLineSeparator(options.lineEnd()); // writes empty lines as well. settings.setSkipEmptyLines(false); }
StringWriter output = new StringWriter(); CsvWriterSettings settings = new CsvWriterSettings(); // many options here, check the documentation ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); String[] headers = new String[columns]; for(int i = 1; i <= columns; i++){ headers[i - 1] = md.getColumnLabel(i); } //if an input value is null, you may want print "NULL" settings.setNullValue("NULL"); // if an input value is not null, but is empty (e.g. ""), the writer can be configured to print "NULL" as well settings.setEmptyValue("NULL"); // Sets the file headers (used for finer selection of fields, these values won't be written automatically) settings.setHeaders(headers); // Creates a writer with the above settings; CsvWriter writer = new CsvWriter(output, settings); // Writes the headers specified in the settings writer.writeHeaders(); Object[] row = new Object[columns]; while(rs.next()){ for(int i = 1; i <= columns; i++){ row[i - 1] = rs.getObject(i); } writer.writeRow(row); } writer.close(); String yourString = output.toString();
settings.setFormat(format); settings.setEmptyValue("\"\""); settings.setNullValue(null);
/** * Private constructor to prevent instantiation */ public CsvWriter(Table table, CsvWriteOptions options) { this.table = table; this.header = options.header(); this.writer = options.writer(); this.settings = new CsvWriterSettings(); // Sets the character sequence to write for the values that are null. settings.setNullValue(nullValue); settings.getFormat().setDelimiter(options.separator()); settings.getFormat().setQuote(options.quoteChar()); settings.getFormat().setQuoteEscape(options.escapeChar()); settings.getFormat().setLineSeparator(options.lineEnd()); // writes empty lines as well. settings.setSkipEmptyLines(false); }