|
2 | 2 |
|
3 | 3 | import java.io.IOException; |
4 | 4 | import java.util.ArrayList; |
| 5 | +import java.util.Collections; |
5 | 6 | import java.util.List; |
6 | 7 |
|
7 | 8 | import org.apache.commons.csv.CSVPrinter; |
|
11 | 12 | import technology.tabula.Table; |
12 | 13 |
|
13 | 14 | public class CSVWriter implements Writer { |
14 | | - |
15 | | - CSVPrinter printer; |
16 | | - private boolean useLineReturns = true; |
17 | | - |
18 | | -// public CSVWriter() { |
19 | | -// super(); |
20 | | -// } |
21 | | -// |
22 | | -// public CSVWriter(boolean useLineReturns) { |
23 | | -// super(); |
24 | | -// this.useLineReturns = useLineReturns; |
25 | | -// } |
26 | | - |
27 | | - void createWriter(Appendable out) { |
28 | | - try { |
29 | | - this.printer = new CSVPrinter(out, CSVFormat.EXCEL); |
30 | | - } catch (IOException e) { |
31 | | - // TODO Auto-generated catch block |
32 | | - e.printStackTrace(); |
33 | | - } |
34 | | - } |
35 | | - |
36 | | - @Override |
37 | | - public void write(Appendable out, Table table) throws IOException { |
38 | | - this.createWriter(out); |
39 | | - for (List<RectangularTextContainer> row: table.getRows()) { |
40 | | - List<String> cells = new ArrayList<String>(row.size()); |
41 | | - for (RectangularTextContainer tc: row) { |
42 | | - cells.add(tc.getText()); |
43 | | - } |
44 | | - this.printer.printRecord(cells); |
45 | | - } |
46 | | - printer.flush(); |
47 | | - } |
| 15 | + |
| 16 | + public CSVWriter() { |
| 17 | + this(CSVFormat.EXCEL); |
| 18 | + } |
| 19 | + |
| 20 | + protected CSVWriter(CSVFormat format) { |
| 21 | + this.format = format; |
| 22 | + } |
| 23 | + |
| 24 | + private final CSVFormat format; |
| 25 | + |
| 26 | + @Override |
| 27 | + public void write(Appendable out, Table table) throws IOException { |
| 28 | + write(out, Collections.singletonList(table)); |
| 29 | + } |
48 | 30 |
|
49 | 31 | @Override |
50 | 32 | public void write(Appendable out, List<Table> tables) throws IOException { |
51 | | - for (Table table : tables) { |
52 | | - write(out, table); |
| 33 | + try (CSVPrinter printer = new CSVPrinter(out, format)) { |
| 34 | + for (Table table : tables) { |
| 35 | + for (List<RectangularTextContainer> row : table.getRows()) { |
| 36 | + List<String> cells = new ArrayList<>(row.size()); |
| 37 | + for (RectangularTextContainer<?> tc : row) cells.add(tc.getText()); |
| 38 | + printer.printRecord(cells); |
| 39 | + } |
| 40 | + } |
| 41 | + printer.flush(); |
53 | 42 | } |
54 | | - |
55 | 43 | } |
56 | 44 |
|
57 | 45 | } |
0 commit comments