Sometimes we need to read/Write data from/to Excel sheet.
Here is the way
1.Create one Excel sheet at any Location(Lets say D:\College.xls)
2.Make sure it is not readOnly(otherwise you cannot write data from Java also)
3.Create/Rename a sheet with name "Student"
4.Create ColumnHeading (Normal way) and write some data into it.
5.Create a ODBC DataSource point to the excel file(College.xls)
Navigate to
Start->Control Panel->Administrative Tools->ODBC->"System Dsn" tab->Click on Add Button-->Select "Driver do MS Excel(*.xls)"-->finish
DataSourceName: xlsdsn
Click on Option button and uncheck Read Only
Click on select Workbook button and choose D:\College.xls click OK
click ok-->ok
ExcelTest.java
Download Code Here
Here is the way
1.Create one Excel sheet at any Location(Lets say D:\College.xls)
2.Make sure it is not readOnly(otherwise you cannot write data from Java also)
3.Create/Rename a sheet with name "Student"
4.Create ColumnHeading (Normal way) and write some data into it.
5.Create a ODBC DataSource point to the excel file(College.xls)
Navigate to
Start->Control Panel->Administrative Tools->ODBC->"System Dsn" tab->Click on Add Button-->Select "Driver do MS Excel(*.xls)"-->finish
DataSourceName: xlsdsn
Click on Option button and uncheck Read Only
Click on select Workbook button and choose D:\College.xls click OK
click ok-->ok
ExcelTest.java
---------------
// ExcelTest.java (reads/writes the records from/to Ms-Excel sheet)
import java.sql.*;
public class ExcelTest
{
public static void main(String args[])throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:xlsdsn");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from [student$]");
while(rs.next()){
System.out.println(rs.getInt("sno")+" "+rs.getString("sname")+" "+rs.getString("sadd"));
}
PreparedStatement ps=con.prepareStatement("insert into [student$] values(?,?,?)");
ps.setInt(1,10);
ps.setString(2,"Raja");
ps.setString(3,"ameerpet");
ps.executeUpdate();
ps.close();
rs.close();
st.close();
con.close();
} // main
} // class
public static void main(String args[])throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:xlsdsn");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from [student$]");
while(rs.next()){
System.out.println(rs.getInt("sno")+" "+rs.getString("sname")+" "+rs.getString("sadd"));
}
PreparedStatement ps=con.prepareStatement("insert into [student$] values(?,?,?)");
ps.setInt(1,10);
ps.setString(2,"Raja");
ps.setString(3,"ameerpet");
ps.executeUpdate();
ps.close();
rs.close();
st.close();
con.close();
} // main
} // class
Download Code Here
No comments:
Post a Comment