How to Open CSV Files in a Microsoft Excel Application Using Java Code
CSV files are comma delimited files created by Microsoft Excel or SQL Server. The file is a list of records with each field separated with a comma. Reading these files in Java is accomplished with a few extra lines of code and an extended library that is downloaded on the Internet. Each file is imported, read, and the information is extracted either for use within the application or displayed to the user.
Instructions
-
-
1
Download the extraction tool at the following location:
http://sourceforge.net/projects/datafile/files
Extract the downloaded files into your Java directory. -
2
Instantiate the class and assign it to a variable. Once the class is instantiated, you can use its methods and properties:
DataFile dataclass = DataFile.createReader("8859_1"); -
-
3
Indicate the file format. The following code opens the file and tells the class that the file format is comma delimited, with the first row indicating the column header names:
dataclass.setDataFormat(new CSVFormat());
dataclass.containsHeader(true); -
4
Import the data into memory. The following syntax opens the CSV file from the hard drive:
dataclass.open(new File("c:\\myfile.csv")); -
5
Read the first row of data. The code below uses the opened file variable to read the first record and store it into a variable for display:
DataRow firstrow = dataclass.next();
String firstrecord = firstrow.getString(0); -
6
Print the record to the console for display. Now the data can be used within the code or displayed to the use. The following code prints it to the screen:
System.out.println(firstrecord);
-
1