CsvWriter implements DataWriter<CsvWriteOptions> { public void write(Table table, CsvWriteOptions options) { CsvWriterSettings settings = createSettings(options); com.univocity.parsers.csv.CsvWriter csvWriter = null; try { csvWriter = new com.univocity.parsers.csv.CsvWriter(options.destination().createWriter(), settings); if (options.header()) { String[] header = new String[table.columnCount()]; for (int c = 0; c < table.columnCount(); c++) { header[c] = table.column(c).name(); } csvWriter.writeHeaders(header); } for (int r = 0; r < table.rowCount(); r++) { String[] entries = new String[table.columnCount()]; for (int c = 0; c < table.columnCount(); c++) { table.get(r, c); entries[c] = table.getUnformatted(r, c); } csvWriter.writeRow(entries); } } finally { if (csvWriter != null) { csvWriter.flush(); csvWriter.close(); } } }  static void register(WriterRegistry registry); void write(Table table, CsvWriteOptions options); @Override void write(Table table, Destination dest);  }
@Test public void toWriterWithExtension() throws IOException { StringColumn colA = StringColumn.create("colA", ImmutableList.of("a", "b")); StringColumn colB = StringColumn.create("colB", ImmutableList.of("1", "2")); Table table = Table.create("testTable", colA, colB); StringWriter writer = new StringWriter(); table.write().toWriter(writer, "csv"); assertEquals("colA,colB\na,1\nb,2\n", writer.toString().replaceAll("\\r\\n", "\n")); }
@Test public void quoteAll() throws IOException { StringColumn colA = StringColumn.create("colA", ImmutableList.of("a", "b")); StringColumn colB = StringColumn.create("colB", ImmutableList.of("1", "2")); Table table = Table.create("testTable", colA, colB); StringWriter writer = new StringWriter(); table.write().usingOptions(CsvWriteOptions.builder(writer).quoteAllFields(true).build()); assertEquals( "\"colA\",\"colB\"\n\"a\",\"1\"\n\"b\",\"2\"\n", writer.toString().replaceAll("\\r\\n", "\n")); }