Importing CSV data with Apache POI

58,048

Solution 1

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 .txt suffix. If it has the .txt suffix, save it as a .csv. All then you have to do is right click on the CSV and Open With Excel. Presto, the CSV has been imported into Excel.

I am assuming that you are wanting to parse the data from a txt file into the Excel File. If that is the case I would suggest you use a Library like SuperCSV instead of trying to get POI to do something it was never designed to do. It will load it all into a Bean, Map or List of your choice as it parses the data and then you can either write it back in the format you chose into a .csv file or use a JDBC-ODBC Bridge or Apache POI to write it directly into and .XLS format. Adds an extra step, but then you have complete control of the data.

SuperCSV carries the Apache2 License, so it should be good for anything you choose to do with it.

Or just use the split function in Java and parse up the CSV into arrays and load the arrays into .xls with POI.

Solution 2

Use apache commons-csv for CSV files. Update your pom.xml with following dependency

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.5</version>
</dependency>

You can find useful good exaples from - click here

Solution 3

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>
Share:
58,048
Jake
Author by

Jake

Quantitative specialist in New York.

Updated on July 23, 2022

Comments

  • Jake
    Jake almost 2 years

    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...?