List of usage examples for org.apache.commons.csv CSVPrinter CSVPrinter
public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException
From source file:com.awesheet.managers.CSVManager.java
/** * Exports the given Sheet to a CSV file in the specified path. * @param sheet the Sheet to export.// w w w .ja va 2 s . c om * @param path the target path of the CSV file. * @return whether the export was successful */ public boolean exportSheet(Sheet sheet, String path) { FileWriter writer = null; CSVPrinter printer = null; try { writer = new FileWriter(path); printer = new CSVPrinter(writer, CSVFormat.RFC4180); // Write records. for (int y = 0; y < sheet.getMaxRow(); ++y) { List<String> values = new ArrayList<String>(); for (int x = 0; x < sheet.getMaxColumn(); ++x) { Cell cell = sheet.getCell(x, y); values.add(cell == null ? "" : cell.getDisplayValue()); } printer.printRecord(values); } } catch (Exception e) { return false; } finally { try { if (writer != null) { writer.flush(); writer.close(); } if (printer != null) { printer.close(); } } catch (Exception ignored) { } } return true; }
From source file:biz.webgate.dominoext.poi.component.kernel.CSVProcessor.java
public ByteArrayOutputStream generateCSV(UICSV csvDef, FacesContext context) throws IOException, POIException { ByteArrayOutputStream csvBAOS = new ByteArrayOutputStream(); OutputStreamWriter csvWriter = new OutputStreamWriter(csvBAOS); CSVPrinter csvPrinter = new CSVPrinter(csvWriter, CSVFormat.DEFAULT); List<CSVColumn> lstColumns = csvDef.getColumns(); Collections.sort(lstColumns, new Comparator<CSVColumn>() { public int compare(CSVColumn o1, CSVColumn o2) { Integer p1 = Integer.valueOf(o1.getPosition()); Integer p2 = Integer.valueOf(o2.getPosition()); return p1.compareTo(p2); }//from w w w. j ava 2 s . c o m }); if (csvDef.isIncludeHeader()) { for (CSVColumn cl : lstColumns) { csvPrinter.print(cl.getTitle()); } csvPrinter.println(); } // DATASOURCE holen und verarbeiten. if (csvDef.getDataSource() != null) { EmbeddedDataSourceExportProcessor.getInstance().process(lstColumns, csvDef, csvPrinter, context); } else { XPagesDataSourceExportProcessor.getInstance().process(lstColumns, csvDef, csvPrinter, context); } csvPrinter.flush(); return csvBAOS; }
From source file:fr.cea.ig.grools.reporter.CSVSensitivitySpecificity.java
public CSVSensitivitySpecificity(@NonNull final File file) throws IOException { super(file);/*from ww w .j a va 2 s. co m*/ this.csvPrinter = new CSVPrinter(bos, format); csvPrinter.printRecord(header); }
From source file:com.anhth12.lambda.common.text.TextUtils.java
private static String doJoinDelimited(Iterable<?> elements, CSVFormat format) { StringWriter out = new StringWriter(); try (CSVPrinter printer = new CSVPrinter(out, format)) { for (Object element : elements) { printer.print(element);//from w w w. j a v a2 s. c o m } printer.flush(); } catch (IOException e) { throw new IllegalStateException(e); } return out.toString(); }
From source file:de.tynne.benchmarksuite.Main.java
private static void runBenchmarks(Args args, BenchmarkProducer benchmarkProducer) throws IOException { BackupHelper.backupIfNeeded(args.getOutput()); // this looks like NOT comma seperated values, but excel and libreoffice load this automatically final CSVFormat format = CSVFormat.EXCEL.withDelimiter(';').withHeader("#", "ID", "Name", "Min [ns]", "Avg [ns]", "Max [ns]", "Chart Pos", "Best Increase [%]", "Iterations"); try (CSVPrinter printer = new CSVPrinter( new OutputStreamWriter(new FileOutputStream(args.getOutput()), Charset.forName(args.getCharset())), format)) {/*from www . j a v a 2 s .c om*/ List<Benchmark> benchmarks = benchmarkProducer.get(); List<Benchmark> matching = benchmarks.stream() .filter(b -> args.getExecute().matcher(b.getId()).matches()).collect(Collectors.toList()); BenchmarkRunner benchmarkRunner = new BenchmarkRunner(matching, BenchmarkRunner.SEC_IN_NANOS * args.getWarumUpTime(), BenchmarkRunner.SEC_IN_NANOS * args.getRunTime()); benchmarkRunner.run(); Chart chart = Chart.of(matching); for (Benchmark b : matching) { try { StatRecord statRecord = chart.getStats().get(b); printer.print(matching.indexOf(b)); printer.print(b.getId()); printer.print(b.getName()); printer.print(format(args, statRecord.getMin())); printer.print(format(args, statRecord.getAverage())); printer.print(format(args, statRecord.getMax())); printer.print(chart.getChart().get(b).chartPosition); double bestAvg = chart.getStats().get(chart.getPerformanceChart().get(0)).getAverage(); double thisAvg = statRecord.getAverage(); printer.print(format(args, 100. * (thisAvg - bestAvg) / bestAvg)); printer.print(statRecord.getCount()); printer.println(); } catch (IOException ex) { ex.printStackTrace(); } } } }
From source file:de.tudarmstadt.ukp.experiments.argumentation.sequence.significance.SignificanceMain.java
/** * Prints table to output string as CSV/*from w w w . j av a2 s .co m*/ * * @param out output * @param <T> value type * @param table table * @throws IOException */ public static <T> String tableToCsv(Table<String, String, Boolean> table) throws IOException { StringWriter sw = new StringWriter(); CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); List<String> firstRow = new ArrayList<>(); firstRow.add(" "); firstRow.addAll(table.columnKeySet()); printer.printRecord(firstRow); for (String rowKey : table.rowKeySet()) { printer.print(rowKey); for (String columnKey : table.columnKeySet()) { printer.print(table.get(rowKey, columnKey)); } printer.println(); } printer.close(); return sw.toString(); }
From source file:de.dhbw.vetaraus.CSV.java
/** * Write a given list of Case objects with a given CSV-delimiter to any Appendable output (i.e. printer). * <p>/*from w w w . j ava 2s . c o m*/ * The output file will include a header record and print the following values: * ID, age, gender, married, children, degree, occupation, income, tariff. * * @param cases * The list of Case objects to write * @param delimiter * The delimiter between each CSV column. * @param out * The Appendable output to which the data should be written. * @throws IOException */ public static void write(List<Case> cases, Character delimiter, Appendable out) throws IOException { try (CSVPrinter writer = new CSVPrinter(out, CSVFormat.DEFAULT.withDelimiter(delimiter))) { // print headers writer.printRecord(Constants.HEADER_NUMBER, Constants.HEADER_AGE, Constants.HEADER_GENDER, Constants.HEADER_MARRIED, Constants.HEADER_CHILDREN, Constants.HEADER_DEGREE, Constants.HEADER_OCCUPATION, Constants.HEADER_INCOME, Constants.HEADER_TARIFF); for (Case c : cases) { writer.printRecord(c.getNumber(), c.getAge(), c.getGender(), c.getMarried(), c.getChildCount(), c.getDegree(), c.getOccupation(), c.getIncome(), c.getTariff()); } writer.flush(); } }
From source file:fr.cea.ig.grools.reporter.CSVReport.java
public CSVReport(@NonNull final String filepath, @NonNull final Reasoner reasoner) throws IOException { super(filepath); this.csvPrinter = new CSVPrinter(bos, format); csvPrinter.printRecord(header);/*from ww w . j a v a2 s. c om*/ }
From source file:com.itemanalysis.jmetrik.file.JmetrikFileExporter.java
private boolean exportFile() { JmetrikFileReader reader = null;//from www .j av a 2 s .c o m BufferedWriter writer = null; CSVPrinter printer = null; if (outputFile.exists() && !overwrite) return false; try { reader = new JmetrikFileReader(dataFile); writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(outputFile.toPath()))); reader.openConnection(); if (hasHeader) { String[] colNames = reader.getColumnNames(); printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#').withDelimiter(delimiter).withHeader(colNames)); } else { printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#').withDelimiter(delimiter)); } LinkedHashMap<VariableName, VariableAttributes> variableAttributes = reader.getVariableAttributes(); JmetrikCSVRecord record = null; VariableAttributes tempAttributes = null; //print scored values if (scored) { String tempValue = ""; while (reader.hasNext()) { record = reader.next(); for (VariableName v : variableAttributes.keySet()) { tempAttributes = variableAttributes.get(v); tempValue = record.originalValue(v); if (tempAttributes.getItemType() == ItemType.NOT_ITEM) { //write original string if not an item if (record.isMissing(v, tempValue) && empty) { printer.print(""); } else { printer.print(tempValue); } } else { //write scored value if a test item if (record.isMissing(v, tempValue) && empty) { printer.print(""); } else { printer.print(tempAttributes.getItemScoring().computeItemScore(tempValue)); } } } printer.println(); } //print original values } else { String tempValue = ""; while (reader.hasNext()) { record = reader.next(); for (VariableName v : variableAttributes.keySet()) { tempValue = record.originalValue(v); if (record.isMissing(v, tempValue) && empty) { printer.print(""); } else { printer.print(tempValue); } } printer.println(); } } } catch (IOException ex) { theException = ex; } finally { try { if (reader != null) reader.close(); if (printer != null) printer.close(); if (writer != null) writer.close(); } catch (IOException ex) { theException = ex; } } return true; }
From source file:javalibs.CSVExtractor.java
/** * Write a single CSV record to a CSV file * @param path The path to save the CSV file * @param rec The record to be written/*from w w w . ja v a2s .c o m*/ * @param headers Headers for the CSV. If this value is null there will be no * headers added to the CSV */ public static void writeCSVRecord(String path, CSVRecord rec, String[] headers) { BufferedWriter bw = null; CSVPrinter printer = null; try { bw = Files.newBufferedWriter(Paths.get(path)); if (headers != null) printer = new CSVPrinter(bw, CSVFormat.DEFAULT.withHeader(headers)); else printer = new CSVPrinter(bw, CSVFormat.DEFAULT); } catch (IOException e) { TSL.get().exception(e); } TSL.get().require(bw != null, "BufferedWriter cannot be null"); TSL.get().require(printer != null, "CSVPrinter cannot be null"); try { printer.printRecord(rec); printer.flush(); } catch (IOException e) { TSL.get().exception(e); } }