1

I'm trying to import CSV files using Java library openCSV. Is there any way to load only specific columns not all of them? My code right now is:

JFileChooser fileopen = new JFileChooser();
                FileFilter filter = new FileNameExtensionFilter(
                        "CSV file", "csv");
                fileopen.addChoosableFileFilter(filter);

                int ret = fileopen.showDialog(null, "Choose file");
                                if (ret == JFileChooser.APPROVE_OPTION) {
    try {
        File file = fileopen.getSelectedFile();
        System.out.println("Opening: " + file.getName());
        File csvFilename = fileopen.getSelectedFile();
        try (CSVReader csvReader = new CSVReader(new FileReader(csvFilename), ',', '\'',11 )) {
            String[] row = null;
            while((row = csvReader.readNext()) != null) {
                System.out.println(row[0]
                        + " # " + row[1]
                        + " #  " + row[2]);
            }
        } 
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Glass_search.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Glass_search.class.getName()).log(Level.SEVERE, null, ex);
    }

    }

This file also got headings so maybe this way?

2 Answers 2

1

For that particular case univocity-parsers is a much better fit as you can easily choose what columns to get:

CsvParserSettings parserSettings = new CsvParserSettings();
settings.detectFormatAutomatically(); //detects the format 

//extracts the headers from the input
settings.setHeaderExtractionEnabled(true);

//or give the header names yourself
// if you use this it will override the headers read from the input (enabled above).
settings.setHeaders("A", "B", "C");

//now for the column selection
settings.selectFields("A", "C"); //rows will contain only values of column "A" and "C"
//or
settings.selectIndexes(0, 2); //rows will contain only values of columns at position 0 and 2

List<String[]> rows = new CsvParser(settings).parseAll(new File("/path/to/your.csv"), "UTF-8");

You can also get the values of each column in a List:

ColumnProcessor columnProcessor = new ColumnProcessor();
settings.setProcessor(columnProcessor);
CsvParser parser = new CsvParser(settings);
parser.parse(new File("/path/to/your.csv), "UTF-8"); //all rows are submitted to the processor created above.

Map<String, List<String>> columnValues = columnProcessor.getColumnValuesAsMapOfNames();

This should solve all your problems, hope it helps.

Disclaimer: I'm the author of this library. It's open-source and free (Apache 2.0 license)

Sign up to request clarification or add additional context in comments.

1 Comment

First one works just perfect, now I'm trying to use file from JFileChooser and upload it to MSSQL database :) Thank you. Your library saved me a lot work.
1

If you create your CSVReader instance using a CSVReaderBuilder you can set your own parser for the reader to use. All you need then is to create your own parser that implements the ICSVParser interface.

1 Comment

ahh crap, that's not my level of exp yet ;) Thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.