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...?
问题:
回答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.
回答2:
The most efficient way to add information to your Excel spreadsheet is by using an array. This code:
Sheets(1).Range("A1").Resize(uBound(myArray),uBound(myArray,2)).Value = myArray
populates the sheet range from a two dimensional array, where the lower bound is 1.
In your situation, I would read the CSV file into an array first, and THEN use syntax like the above to place it on the worksheet.
Stan Scott
回答3:
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
回答4:
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>