skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Wednesday, September 19, 2012

Java - Excel Connectivity

Posted by Admin at 9:45 AM – 0 comments
 

This contains the sample code for Java Excel Connectivity


import java.sql.*;
import java.io.*;
import java.util.*;
import java.text.*;
/**
 *
 * Name: Excel.java
 *
 * Purpose: To demonstrate how to use ODBC and Excel to create
 * a table, insert data into it, and select it back out.
 *
 * Version: Developed using JDK 1.3
 *
 * Instructions:
 *
 * 1) Create a new Excel spreadsheet
 *
 * 2) Create a new ODBC data source that points to this
 * spreadsheet
 *
 * a) Go to Control Panel
 * b) Open "ODBC Data sources (32-bit) (wording may be
 * slightly different for different platforms)
 * c) Under "User DSN" tab, press "Add" button
 * d) Select the "Microsoft Excel Driver (*.xls)" and
 * press "Finish" button
 * e) Enter "Data Source Name" of "TestExcel"
 * f) Press "Select Workbook" button
 * g) Locate and select the spreadsheet you created in
 * Step 1
 * h) Unselect the "Read Only" checkbox
 * i) Press "Ok" button
 *
 * 3) Compile and run Excel.java
 *
 *
 * Notes:
 * If you want to select data from a spreadsheet that was
 * NOT created via JDBC-ODBC (i.e. you entered data manually
 * into a spreadsheet and want to select it out), you must
 * reference the sheet name as "[sheetname$]".
 *
 * When you create the table and insert the data using
 * Java, you must reference the sheet name as "sheetname".
 *
 * Also, do not have the spreadsheet open when you are
 * running the program. You can get locking conflicts.
 *
 *
 */
public class Excel
{
 public void readexel(String filename)
 {
 Connection c = null;
 Statement stmnt = null;
 try
 {
 Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
 c = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=" + filename);
 stmnt = c.createStatement();
 String query = "Select * from [Sheet1$]" ;
 ResultSet rs = stmnt.executeQuery( query );

 while( rs.next() )
 {
 System.out.println( rs.getString(1) );
 System.out.println("\n");
 }
 }
 catch( Exception e )
 {
 System.err.println( e );
 }

 } 
 public static void main(String args[]){
   System.out.println("main() begin");
   String file = "C:/Example/test.xls";
   Excel lExcel = new Excel();
   lExcel.readexel(file);
   message("main() end");
   System.exit(0);
  }
}


Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger