Example usage for org.apache.commons.csv CSVFormat EXCEL

List of usage examples for org.apache.commons.csv CSVFormat EXCEL

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVFormat EXCEL.

Prototype

CSVFormat EXCEL

To view the source code for org.apache.commons.csv CSVFormat EXCEL.

Click Source Link

Document

Excel file format (using a comma as the value delimiter).

Usage

From source file:com.tutuka.io.CSVFileReader.java

public List<TransactionRecord> loadFileIntoList() throws IOException {
    Reader in;/*from   w w w  .ja  va2  s  .c o m*/
    if (handlePart) {
        in = new InputStreamReader(tutukaFile.getInputStream());
    } else {
        in = new FileReader(fileLocation);
    }

    Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in);

    List<TransactionRecord> trecList;
    trecList = new ArrayList<>();
    for (CSVRecord rec : records) {
        TransactionRecord trec = new TransactionRecord();
        trec.setTransactionID(rec.get("TransactionID"));
        trecList.add(trec);
    }
    return trecList;
}

From source file:com.test.goeuro.csvGenerator.CSVFileGenerator.java

/**
 *
 * @param respondArray//from  w  w w  .  ja  va2  s.  com
 */
public void createCSVFileAndWriteData(JsonArray respondArray) throws FileNotFoundException, IOException {

    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;
    CSVFormat csvFileFormat = CSVFormat.EXCEL.withRecordSeparator(NEW_LINE_SEPARATOR);
    try {
        System.out.println("generating CVS file ....");
        fileWriter = new FileWriter(new File(Constants.FILE_NAME));
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
        csvFilePrinter.printRecord(FILE_HEADER);

        for (JsonElement jsonElement : respondArray) {
            List apiRespondData = new ArrayList();
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            apiRespondData.add(jsonObject.get(Constants._ID).getAsString());
            apiRespondData.add(jsonObject.get(Constants.NAME).getAsString());
            apiRespondData.add(jsonObject.get(Constants.TYPE).getAsString());
            JsonObject inGeoPosObject = jsonObject.getAsJsonObject(Constants.GEO_POSITION);
            apiRespondData.add(inGeoPosObject.get(Constants.LATITUDE).getAsDouble());
            apiRespondData.add(inGeoPosObject.get(Constants.LONGITUDE).getAsDouble());
            csvFilePrinter.printRecord(apiRespondData);
        }

        System.out.println("CSV generated successfully");
    } catch (FileNotFoundException fnfex) {
        Logger.getLogger(CSVFileGenerator.class.getName()).log(Level.SEVERE, null, fnfex);
        System.out.println("Error in Open csv file");
        fnfex.printStackTrace();
    } catch (IOException ioex) {
        Logger.getLogger(CSVFileGenerator.class.getName()).log(Level.SEVERE, null, ioex);
        System.out.println("Error in Open/Write CsvFileWriter!!!");
        ioex.printStackTrace();
    } finally {
        try {
            fileWriter.flush();
            fileWriter.close();
            csvFilePrinter.close();
        } catch (IOException e) {
            System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
            e.printStackTrace();
        } catch (Exception ex) {
            System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
            ex.printStackTrace();
        }
    }
}

From source file:com.mycompany.couchdb.CsvManage.java

public boolean hello() throws FileNotFoundException, IOException {
    int count = 0;
    String filename = "src/main/resources/GeoLiteCity-Location.csv";
    City city;/*from   ww  w.j  av  a 2 s . c om*/
    DataDealer cityDao;

    cityDao = new DataDealer();

    Reader in = new FileReader(filename); //read file
    CSVParser parser = new CSVParser(in, CSVFormat.EXCEL.withHeader()); //create parser
    city = new City();
    for (CSVRecord record : parser) {
        //parse file and create objects

        //city.setLocId(Integer.parseInt(record.get("locId")));
        //city.setCountry(record.get("country"));
        city.setCity(record.get("city"));
        //city.setRegion(record.get("region"));
        city.setLatitude(Float.parseFloat(record.get("latitude")));
        city.setLongitude(Float.parseFloat(record.get("longitude")));

        //

        try {
            cityDao.save(city);

        } finally {
            cityDao.finalize();
        }

    }
    return true;
}

From source file:jgnash.convert.exportantur.csv.CsvExport.java

public static void exportAccount(final Account account, final LocalDate startDate, final LocalDate endDate,
        final File file) {
    Objects.requireNonNull(account);
    Objects.requireNonNull(startDate);
    Objects.requireNonNull(endDate);
    Objects.requireNonNull(file);

    // force a correct file extension
    final String fileName = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".csv";

    final CSVFormat csvFormat = CSVFormat.EXCEL.withQuoteMode(QuoteMode.ALL);

    try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
            Files.newOutputStream(Paths.get(fileName)), StandardCharsets.UTF_8);
            final CSVPrinter writer = new CSVPrinter(new BufferedWriter(outputStreamWriter), csvFormat)) {

        outputStreamWriter.write('\ufeff'); // write UTF-8 byte order mark to the file for easier imports

        writer.printRecord("Account", "Number", "Debit", "Credit", "Balance", "Date", "Timestamp", "Memo",
                "Payee", "Reconciled");

        // write the transactions
        final List<Transaction> transactions = account.getTransactions(startDate, endDate);

        final DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendValue(MONTH_OF_YEAR, 2).appendValue(DAY_OF_MONTH, 2).toFormatter();

        final DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendLiteral('-').appendValue(MONTH_OF_YEAR, 2).appendLiteral('-')
                .appendValue(DAY_OF_MONTH, 2).appendLiteral(' ').appendValue(HOUR_OF_DAY, 2).appendLiteral(':')
                .appendValue(MINUTE_OF_HOUR, 2).appendLiteral(':').appendValue(SECOND_OF_MINUTE, 2)
                .toFormatter();/*from   w w  w  . j  a  v a  2 s  .c  om*/

        for (final Transaction transaction : transactions) {
            final String date = dateTimeFormatter.format(transaction.getLocalDate());

            final String timeStamp = timestampFormatter.format(transaction.getTimestamp());

            final String credit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) < 0 ? ""
                    : transaction.getAmount(account).abs().toPlainString();

            final String debit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) > 0 ? ""
                    : transaction.getAmount(account).abs().toPlainString();

            final String balance = account.getBalanceAt(transaction).toPlainString();

            final String reconciled = transaction.getReconciled(account) == ReconciledState.NOT_RECONCILED
                    ? Boolean.FALSE.toString()
                    : Boolean.TRUE.toString();

            writer.printRecord(account.getName(), transaction.getNumber(), debit, credit, balance, date,
                    timeStamp, transaction.getMemo(), transaction.getPayee(), reconciled);
        }
    } catch (final IOException e) {
        Logger.getLogger(CsvExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
}

From source file:innovimax.quixproc.datamodel.in.csv.CSVQuiXEventStreamReader.java

private AQuiXEvent load(final CSVStreamSource source) {

    try {/* w ww  .  j av a2 s. c o  m*/
        this.parser = CSVFormat.EXCEL.parse(source.asReader());
        this.iter = this.parser.iterator();
    } catch (final IOException e) {
        throw new QuiXException(e);
    }
    this.buffer.add(AQuiXEvent.getStartArray());
    return AQuiXEvent.getStartTable();
}

From source file:de.thomasvolk.genexample.model.CSVPassagierFactory.java

@Override
protected List<Passagier> lesePassagiere(InputStream is, int anzahl) throws IOException {
    List<Passagier> passagiere = new ArrayList<>();
    Reader in = new InputStreamReader(is);
    Iterator<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in).iterator();
    int i = 0;/*from   w  w w  . ja  va  2 s . com*/
    while (records.hasNext() && i < anzahl) {
        CSVRecord record = records.next();
        i++;
        int fahrtrichtung = getWertung(record.get(IN_FAHRTRICHTUNG));
        int fensterplatz = getWertung(record.get(FENSTERPLATZ));
        int abteil = getWertung(record.get(ABTEIL));
        Wertung wertung = new Wertung(fensterplatz, abteil, fahrtrichtung);
        passagiere.add(new Passagier(i, wertung));
    }
    return passagiere;
}

From source file:loternik.MyService.java

public String getHelloMessage(String teryt, String okreg) {
    FileReader file = null;/*from   www .  j a  v a  2  s .c  o  m*/
    try {
        String output = "";

        file = new FileReader("kandydaci.csv");
        CSVParser parser = new CSVParser(file, CSVFormat.EXCEL.withHeader().withDelimiter(';'));
        for (CSVRecord csvRecord : parser) {
            if (teryt.equals(csvRecord.get("teryt")) && okreg.equals(csvRecord.get("Okreg"))) {
                output += "<p>" + csvRecord.toString() + "</p>";
            }
        }
        return output;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MyService.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MyService.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            file.close();
        } catch (IOException ex) {
            Logger.getLogger(MyService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return null;
}

From source file:br.edimarmanica.trinity.check.CheckNrPages.java

private int nrPagesExtracted() {
    Set<String> pages = new HashSet<>();
    File dir = new File(Paths.PATH_TRINITY + site.getPath() + "/offset");

    if (!dir.exists()) {
        return 0;
    }//  ww w . j a  v a 2s.  co m

    for (File offset : dir.listFiles()) {

        try (Reader in = new FileReader(offset)) {
            try (CSVParser parser = new CSVParser(in, CSVFormat.EXCEL)) {
                for (CSVRecord record : parser) {
                    pages.add(record.get(0));
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(CheckNrPages.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CheckNrPages.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return pages.size();
}

From source file:br.edimarmanica.trinity.check.CheckOffsetRule.java

public void execute() {

    File dir = new File(Paths.PATH_TRINITY + site.getPath() + "/offset");

    List<List<String>> offset = new ArrayList<>(); //cada arquivo  um offset

    try (Reader in = new FileReader(dir.getAbsoluteFile() + "/result_" + indexOffset + ".csv")) {
        try (CSVParser parser = new CSVParser(in, CSVFormat.EXCEL)) {
            int nrRegistro = 0;
            for (CSVRecord record : parser) {
                if (nrRegistro >= nrRegistros) {
                    break;
                }//from  w  w  w.j ava2s  .  c  o  m

                System.out.println(record.get(0) + ";" + record.get(indexRule));
                nrRegistro++;
            }
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(CheckOffsetRule.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(CheckOffsetRule.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:convertCSV.ConvertCSV.java

/**
 * @param fichier_/*from w  w w. j a  v  a 2 s  . c  o m*/
 * @throws java.io.IOException
 */
public void importer(String fichier_) throws IOException {
    // TODO code application logic here

    float lat, lon, ele, secjour;
    int bpm;
    List<MonPoint> points = new ArrayList<>();
    Reader in = null;
    CSVParser parser;
    List<CSVRecord> list;
    GPXWriter monGPX = new GPXWriter();

    // lecture du CSV
    try {

        System.out.println("Lecture de " + fichier_);
        in = new FileReader(fichier_);

    } catch (FileNotFoundException ex) {
        Logger.getLogger(ConvertCSV.class.getName()).log(Level.SEVERE, null, ex);
    }

    parser = new CSVParser(in, CSVFormat.EXCEL);
    list = parser.getRecords();
    list.remove(0);

    // remplissage de la liste de point GPX
    if (in != null) {
        for (CSVRecord elem : list) {

            try {

                // on recupere les donnees dans le CSV
                lat = Float.parseFloat(elem.get(0));
                lon = Float.parseFloat(elem.get(1));
                ele = Float.parseFloat(elem.get(2));
                secjour = Float.parseFloat(elem.get(3));
                if (elem.size() > 4) {
                    bpm = Integer.parseInt(elem.get(4));
                    points.add(new MonPoint(lat, lon, ele, secjour, bpm));
                } else {
                    points.add(new MonPoint(lat, lon, ele, secjour));
                }

            } catch (NumberFormatException ex) {
                System.out.println(elem.toString());
            }

        }

        // ecriture du GPX
        monGPX.writePath("C:\\Users\\vincent\\Desktop\\today.gpx", "Training", points);
        in.close();

    }

    System.exit(0);
}