Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing CSV data with Apache POI

How can I efficiently import CSV data with Apache POI? If I have a very large CSV file that I would like to store in my Excel spreadsheet, then I don't imagine that going cell-by-cell is the best way to import...?

like image 431
Jake Avatar asked Apr 06 '09 14:04

Jake


People also ask

Can we use Apache POI for CSV files?

Apache POI was never designed to call on CSV files. While a CSV File may be opened in Excel, Excel has its own reader that does an auto import. This is assuming that your CSV has the . csv instead of the .

How does Apache Commons read CSV files?

csv . It's very easy to read such CSV files with Apache Commons CSV. You just need to add a single setting called withFirstRecordAsHeader() . Apache Commons CSV uses the first record as the header record and allows you to retrieve the values using the header names.


1 Answers

We write the java code based on the file extension. Here we are dealing with .csv extension and here is the Apache POI code to handle it. We split the content and store in Array and then use it down the line.

CSVParser parser = new CSVParser(new FileReader("D:/your_file.csv"), CSVFormat.DEFAULT);
List<CSVRecord> list = parser.getRecords();
for (CSVRecord record : list) {
    String[] arr = new String[record.size()];
    int i = 0;
    for (String str : rec) {
        arr[i++] = str;
    }
}  
parser.close();    

Related Maven Dependency:

<dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.2</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.5</version>
</dependency>
<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>4.2</version>
</dependency>
like image 56
mannedear Avatar answered Sep 17 '22 15:09

mannedear