As we know,
an excel file is a spreadsheet which represents our data in tabular form ( an
intersection of row and column). We all add our database tables in our java
programs using JDBD and ODBC ( a bridge) between Java (a high level language)
and a RDBMS ( a Structured Query Language). If you want to know the database
connectivity in java then go my blog JDBC-ODBC Connectivity using Java. But in
this block I am going to educate you people, How we can use data of excel file
in our java program.
To use an
excel file in java first we have to convert it in a .CSV (comma separated values)
file.
You all must
be knowing the creation of excel file and entering data like
This is an
excel spreadsheet. Now to convert it in .csv file, we have to save this file
with an extension as .csv like as follows :-
After saving
an excel file in .csv extension. We can open this file using simple notepad
also which will show the comma separated file which further we can us in java
by using bufferreader class. When you open your .csv file with an editor like
notepad it will looks like :-
Which is a
simple comma separated flat file. Now write a program to read this text file in
java,C, C++ any language of your choice.
I am
including code in java for reading a simple .csv file.
Country.java
import
java.io.BufferedReader;
import
java.io.FileReader;
import
java.io.IOException;
class
CSVReader {
public static void main(String[] args) {
String csvFile =
"country.csv";
String line = "";
String cvsSplitBy = ",";
try (BufferedReader br = new
BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) !=
null) {
// use comma as separator
String[] country =
line.split(cvsSplitBy);
System.out.println("Country
[code= " + country[0] + " , name=" + country[1] +
"]");
}
} catch (IOException e) {
e.printStackTrace();
} }
}
Now compile
it an run this file and got the result like :-
I am sure
this blog will help you.
No comments:
Post a Comment