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...?
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 .
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With