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:org.jboss.jbossset.CommandLineParser.java

public CommandLineParser(String[] args) {
    this.args = args;

    validCSVFormats = new HashMap<>();
    validCSVFormats.put("excel", CSVFormat.EXCEL);
    validCSVFormats.put("mysql", CSVFormat.MYSQL);
    validCSVFormats.put("rfc4180", CSVFormat.RFC4180);
    validCSVFormats.put("tdf", CSVFormat.TDF);

    addOptions();//from ww  w .j a v  a  2  s .c  o m
}

From source file:org.jvalue.ods.processor.adapter.CsvSourceAdapter.java

@Inject
CsvSourceAdapter(@Assisted DataSource source,
        @Assisted(SourceAdapterFactory.ARGUMENT_SOURCE_URL) String sourceUrl,
        @Assisted(SourceAdapterFactory.ARGUMENT_CSV_FORMAT) String csvFormatString, MetricRegistry registry) {

    super(source, sourceUrl, registry);
    switch (csvFormatString) {
    case "DEFAULT":
        csvFormat = CSVFormat.DEFAULT;//w w w  .  ja va2 s . c o m
        break;

    case "EXCEL":
        csvFormat = CSVFormat.EXCEL;
        break;

    case "MYSQL":
        csvFormat = CSVFormat.MYSQL;
        break;

    case "RFC4180":
        csvFormat = CSVFormat.RFC4180;
        break;

    case "TDF":
        csvFormat = CSVFormat.TDF;
        break;

    default:
        throw new IllegalArgumentException("unknown csv format \"" + csvFormatString + "\"");
    }
}

From source file:org.kisoonlineapp.kisoonlineapp.csv.Csv2Sql.java

void execute() throws IOException {

    switch (this.mode) {
    case Veranstaltung: {
        //final String inFileKisoVeranstaltung = "Kiso2015 - Veranstaltung.csv";
        final String inFileKisoVeranstaltung = this.inputFilename;
        final AbstractKisoConverter kisoVeranstalter = new AbstractKisoConverter(inFileKisoVeranstaltung) {

            @Override/*from   w ww.j ava 2  s .com*/
            AbstractOutputTemplate createOutputTemplate(PrintWriter pw) {
                final KisoVeranstaltungOutputTemplate kisoVeranstaltungOutputTemplate = new KisoVeranstaltungOutputTemplate(
                        pw);
                return kisoVeranstaltungOutputTemplate;
            }

        };
        final CSVFormat csvFormat = CSVFormat.EXCEL.withHeader();
        kisoVeranstalter.convertKisoVeranstaltung(csvFormat);
    }
        break;
    case Veranstalter: {
        //final String inFileKisoVeranstalter = "Kiso2015 - Veranstalter.csv";
        final String inFileKisoVeranstalter = this.inputFilename;
        final AbstractKisoConverter kisoConverter = new AbstractKisoConverter(inFileKisoVeranstalter) {
            @Override
            AbstractOutputTemplate createOutputTemplate(PrintWriter pw) {
                final KisoVeranstalterOutputTemplate kisoVeranstalterOutputTemplate = new KisoVeranstalterOutputTemplate(
                        pw);
                return kisoVeranstalterOutputTemplate;
            }

        };
        final CSVFormat csvFormat = CSVFormat.EXCEL.withHeader();
        kisoConverter.convertKisoVeranstaltung(csvFormat);
    }
        break;
    case None: {
    }
        break;
    default:
    }

}

From source file:org.kuali.test.runner.execution.TestExecutionContext.java

private void writePerformanceDataFile(File f) {
    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;//  w w w .  ja  v a  2 s .co  m

    //Create the CSVFormat object with "\n" as a record delimiter
    CSVFormat csvFileFormat = CSVFormat.EXCEL.withRecordSeparator("\n");

    try {
        //initialize FileWriter object
        fileWriter = new FileWriter(f);

        //initialize CSVPrinter object
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

        //Create CSV file header
        csvFilePrinter.printRecord(Arrays.asList(PERFORMANCE_DATA_HEADER));

        //Write a new student object list to the CSV file
        for (String[] rec : performanceData) {
            csvFilePrinter.printRecord(Arrays.asList(rec));
        }
    }

    catch (Exception ex) {
        LOG.error(ex.toString(), ex);
    }

    finally {
        try {
            if (fileWriter != null) {
                fileWriter.flush();
                fileWriter.close();
            }
        }

        catch (Exception e) {
        }

        try {
            if (csvFilePrinter != null) {
                csvFilePrinter.close();
            }
        }

        catch (Exception e) {
        }
    }
}

From source file:org.neo4art.colour.manager.VanGoghArtworksColourAnalysisDefaultManager.java

/**
 * @see org.neo4art.colour.manager.VanGoghArtworksColourAnalysisManager#loadArtworksFromFile(java.lang.String)
 *///from  www. j a  v  a  2  s  .  c o  m
@Override
public List<Artwork> loadArtworksFromFile(String fileName) throws IOException {
    List<Artwork> artworks = null;

    URL url = getClass().getClassLoader().getResource(fileName);

    CSVParser csvParser = CSVParser.parse(url, Charset.defaultCharset(),
            CSVFormat.EXCEL.withIgnoreSurroundingSpaces(true));

    List<CSVRecord> cvsRecords = csvParser.getRecords();

    if (CollectionUtils.isNotEmpty(cvsRecords) && CollectionUtils.size(cvsRecords) > 1) {
        artworks = new ArrayList<Artwork>();

        for (int i = 1; i < cvsRecords.size(); i++) {
            CSVRecord csvRecord = cvsRecords.get(i);

            Artwork artwork = new Artwork();

            Calendar completionDate = Calendar.getInstance();
            completionDate.set(Calendar.YEAR, Integer.parseInt(csvRecord.get(2)));
            completionDate.set(Calendar.MONTH, Integer.parseInt(csvRecord.get(3)));

            artwork.setTitle(csvRecord.get(0));
            artwork.setType(csvRecord.get(1));
            artwork.setYear(new Date(Integer.parseInt(csvRecord.get(2)), Calendar.JANUARY, 1));
            artwork.setCompletionDate(completionDate.getTime());
            artwork.setImageFile(csvRecord.get(4));
            artwork.setCatalogue("F: " + csvRecord.get(5) + ", JH: " + csvRecord.get(6));

            artworks.add(artwork);
        }
    }

    return artworks;
}

From source file:org.neo4art.core.service.ArtistsArtworkCatalogTest.java

@Test
public void shouldSaveColours() {
    try {/*from ww  w  . j a  v  a  2  s.c  o m*/
        URL url = getClass().getClassLoader().getResource("artists-artworks-catalog.csv");
        CSVParser csvParser = CSVParser.parse(url, Charset.forName("ISO-8859-1"), CSVFormat.EXCEL);

        List<CSVRecord> records = csvParser.getRecords();

        if (CollectionUtils.isNotEmpty(records)) {
            // AUTHOR;BORN-DIED;TITLE;DATE;TECHNIQUE;LOCATION;URL;FORM;TYPE;SCHOOL;TIMEFRAME

            for (int i = 1; i < records.size(); i++) {
                CSVRecord csvRecord = records.get(i);

                String record0 = csvRecord.get(0);

                if (record0.contains(",")) {
                    String[] author = StringUtils.split(record0, ',');
                    System.out.println(WordUtils.capitalizeFully(StringUtils.trim(author[1])));
                    System.out.println(WordUtils.capitalizeFully(StringUtils.trim(author[0])));
                    System.out.println();
                } else {
                    System.out.println(csvRecord.get(0));
                    System.out.println();
                }
                /*
                String record1 = csvRecord.get(1);
                System.out.println("--|" + record1 + "|--");
                        
                if (record1.startsWith("(b. ") && record1.contains("d.") && record1.contains(")"))
                {
                  record1 = StringUtils.remove(record1, '(');
                  record1 = StringUtils.remove(record1, ')');
                  System.out.println(record1);
                  String[] bornDied = StringUtils.split(record1, ',');
                  System.out.println(bornDied[0].trim().substring(2).trim());
                  System.out.println(bornDied[1].trim());
                  System.out.println(bornDied[2].trim().substring(2).trim());
                  System.out.println(bornDied[3].trim());
                }
                else
                {
                  System.out.println(csvRecord.get(1));            
                }
                        
                System.out.println(csvRecord.get(2));
                System.out.println(csvRecord.get(3));
                System.out.println(csvRecord.get(4));
                System.out.println(csvRecord.get(5));
                System.out.println(csvRecord.get(6));
                System.out.println(csvRecord.get(7));
                System.out.println(csvRecord.get(8));
                System.out.println(csvRecord.get(9));
                System.out.println(csvRecord.get(10));
                System.out.println();
                */
            }
        }
    } catch (Exception e) {
        e.printStackTrace();

        Assert.fail(e.getMessage());
    }
}

From source file:org.neo4art.core.service.ColourDefaultService.java

/**
 * @throws IOException //from  w  w  w  .  j  a v a2s  . c o m
 * @see org.neo4art.core.service.ColourService#getColours()
 */
@Override
public List<Colour> getColours() throws IOException {
    List<Colour> result = null;

    URL url = getClass().getClassLoader().getResource("colours.csv");
    CSVParser csvParser = CSVParser.parse(url, Charset.defaultCharset(), CSVFormat.EXCEL.withDelimiter(',')
            .withQuote('\'').withEscape('\\').withIgnoreSurroundingSpaces(true));

    List<CSVRecord> records = csvParser.getRecords();

    if (CollectionUtils.isNotEmpty(records)) {
        result = new ArrayList<Colour>();

        for (CSVRecord csvRecord : records) {
            int r = Integer.parseInt(csvRecord.get(1).substring(1, 3), 16);
            int g = Integer.parseInt(csvRecord.get(1).substring(3, 5), 16);
            int b = Integer.parseInt(csvRecord.get(1).substring(5, 7), 16);

            result.add(new Colour(csvRecord.get(0), r, g, b));
        }
    }

    return result;
}

From source file:org.neo4art.literature.manager.VanGoghLettersManager.java

public List<SentimentAnalysis> loadSentimentsFromFile(String fileName) throws IOException {

    List<SentimentAnalysis> sentimentAnalysisList = new ArrayList<SentimentAnalysis>();

    URL url = getClass().getClassLoader().getResource(fileName);

    CSVParser csvParser = CSVParser.parse(url, Charset.defaultCharset(),
            CSVFormat.EXCEL.withIgnoreSurroundingSpaces(true));

    List<CSVRecord> cvsRecords = csvParser.getRecords();

    if (CollectionUtils.isNotEmpty(cvsRecords) && CollectionUtils.size(cvsRecords) > 1) {

        for (int i = 1; i < cvsRecords.size(); i++) {
            CSVRecord csvRecord = cvsRecords.get(i);

            SentimentAnalysis sentimentAnalysis = new SentimentAnalysis();
            Letter letter = new Letter();
            letter.setTitle(csvRecord.get(0));
            String polarityType = csvRecord.get(1);
            String polarity = "";

            if (polarityType.equalsIgnoreCase("0")) {
                polarity = "neutral";
            } else if (polarityType.equalsIgnoreCase("1") || polarityType.equalsIgnoreCase("2")) {
                polarity = "negative";
            } else if (polarityType.equalsIgnoreCase("3") || polarityType.equalsIgnoreCase("4")) {
                polarity = "positive";
            }// w w w  . jav  a 2  s  . c o  m

            letter.setDate(csvRecord.get(2));

            sentimentAnalysis.setPolarity(polarity);
            sentimentAnalysis.setSource(letter);

            sentimentAnalysisList.add(sentimentAnalysis);
        }
    }

    return sentimentAnalysisList;
}

From source file:org.ohdsi.whiteRabbit.WhiteRabbitMain.java

private DbSettings getTargetDbSettings() {
    DbSettings dbSettings = new DbSettings();
    if (targetType.getSelectedItem().equals("Delimited text files")) {
        dbSettings.dataType = DbSettings.CSVFILES;

        switch ((String) targetCSVFormat.getSelectedItem()) {
        case "Default (comma, CRLF)":
            dbSettings.csvFormat = CSVFormat.DEFAULT;
            break;
        case "RFC4180":
            dbSettings.csvFormat = CSVFormat.RFC4180;
            break;
        case "Excel CSV":
            dbSettings.csvFormat = CSVFormat.EXCEL;
            break;
        case "TDF (tab, CRLF)":
            dbSettings.csvFormat = CSVFormat.TDF;
            break;
        case "MySQL (tab, LF)":
            dbSettings.csvFormat = CSVFormat.MYSQL;
            break;
        default://  w  ww.j  a v a 2  s .  com
            dbSettings.csvFormat = CSVFormat.RFC4180;
        }

    } else {
        dbSettings.dataType = DbSettings.DATABASE;
        dbSettings.user = targetUserField.getText();
        dbSettings.password = targetPasswordField.getText();
        dbSettings.server = targetServerField.getText();
        dbSettings.database = targetDatabaseField.getText();
        if (targetType.getSelectedItem().toString().equals("MySQL"))
            dbSettings.dbType = DbType.MYSQL;
        else if (targetType.getSelectedItem().toString().equals("Oracle"))
            dbSettings.dbType = DbType.ORACLE;
        else if (sourceType.getSelectedItem().toString().equals("PostgreSQL"))
            dbSettings.dbType = DbType.POSTGRESQL;
        else if (sourceType.getSelectedItem().toString().equals("SQL Server")) {
            dbSettings.dbType = DbType.MSSQL;
            if (sourceUserField.getText().length() != 0) { // Not using windows authentication
                String[] parts = sourceUserField.getText().split("/");
                if (parts.length == 2) {
                    dbSettings.user = parts[1];
                    dbSettings.domain = parts[0];
                }
            }
        } else if (sourceType.getSelectedItem().toString().equals("PDW")) {
            dbSettings.dbType = DbType.PDW;
            if (sourceUserField.getText().length() != 0) { // Not using windows authentication
                String[] parts = sourceUserField.getText().split("/");
                if (parts.length == 2) {
                    dbSettings.user = parts[1];
                    dbSettings.domain = parts[0];
                }
            }
        }

        if (dbSettings.database.trim().length() == 0) {
            String message = "Please specify a name for the target database";
            JOptionPane.showMessageDialog(frame, StringUtilities.wordWrap(message, 80), "Database error",
                    JOptionPane.ERROR_MESSAGE);
            return null;
        }
    }
    return dbSettings;
}

From source file:org.oneandone.gitter.out.CSVConsumer.java

public void consume(Map<String, Map<?, ?>> perProjectResults, Function<Object, String> keyFormatter,
        Function<Object, String> valueFormatter, Supplier<Object> nullValue) throws IOException {
    List<String> projects = perProjectResults.keySet().stream().sorted().collect(Collectors.toList());
    List<String> headers = new ArrayList<>(projects);
    headers.add(0, "Key");
    CSVPrinter printer = CSVFormat.EXCEL.withHeader(headers.toArray(new String[0])).print(p);

    Set<Object> keys = perProjectResults.values().stream().flatMap(m -> m.keySet().stream())
            .collect(Collectors.toSet());
    TreeSet<Object> sortedKeys = new TreeSet<>(keys);

    sortedKeys.stream().forEachOrdered(key -> {
        List<String> values = new ArrayList<>();
        values.add(keyFormatter.apply(key));
        projects.forEach(project -> {
            Object obj = perProjectResults.get(project).get(key);
            if (obj == null) {
                obj = nullValue.get();/*from  w  w w  . jav  a 2  s .com*/
            }
            Objects.requireNonNull(obj,
                    () -> "Object at key " + keyFormatter.apply(key) + " for project " + project + " is null");
            values.add(obj != null ? valueFormatter.apply(obj) : "<null>");
        });
        try {

            printer.printRecord(values);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });
}