How to read Excel file in java

Respected sir/madam
I want to read the values from Excel file in Java program. How can I do that. When I searched over the net I came to know that you can treat Excel file as a Database and write the code as u write for making DB connections .
I did that but i am getting the following error ..can anybody please help..
This is the code what i have written
import java.io.*;
import java.sql.*;
public class ReadExcelFile {
Connection c;
Statement stmnt;
public void checkABA_Number()
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c = DriverManager.getConnection("jdbc:odbc:ExcelTest","",""); // ExcelTest is the DSN name
stmnt = c.createStatement();
ResultSet rs = stmnt.executeQuery("select * from abadata"); // abadata is my Excel file name
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2));
}catch(Exception e)
System.out.println(""+e.toString());
finally
try
stmnt.close();
c.close();
catch( Exception e )
System.err.println( e );
public static void main(String[] args)
new ReadExcelFile().checkABA_Number();
My Excel file starts from the first row and first column and also the first row contains the names of the column.
It give me the following error..
java.sql.SQLException: [Microsoft][ODBC Excel Driver] The Microsoft Jet database engine could not find the object 'abadata'. Make sure the object exists and that you spell its name and the path name correctly.
How can I deal with this.?I have properly selected the worksheet while giving the DSN . Is there any versionig problem with Excel or some drivers are in appropriate..and yes i chose Microsoft Excel Driver (.xsl) from ODBC .
I created System DSN.
Can anybody please help me with this ? I will be very gratefull for replies
Thanks in advance

here is the code to read excel file
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) );
catch( Exception e )
System.err.println( e );
}

Similar Messages

  • How To Read RTF file in JAVA?  Using  iText?

    How To Read RTF file in JAVA?  Using  iText?.....
    import java.io.*;
    import com.lowagie.text.*;
    import com.lowagie.text.rtf.*;
    public class RTF3 {
    public static void main(String[] args) {
    // System.out.println("This example generate a RTF file name Sample.rtf");
    // Create Document object
    Document myDoc = new Document();
    try {
    // Create writer to listen document object
    // and directs RTF Stream to the file Sample.rtf
    RtfWriter2.getInstance(myDoc, new FileOutputStream("Sample.rtf"));
    // open the document object
    myDoc.open();
    // Create a paragraph
         Paragraph p = new Paragraph();
         p.add("Helloworld in Rtf file..amazing isn't");
         // Add the paragraph to document object
    myDoc.add(p);
    catch(Exception e) {
    System.out.println(e);
    //close the document
    myDoc.close();
    Exception in thread "main" java.lang.NoSuchMethodError: com.lowagie.text.Rectangle.width()F
         at com.lowagie.text.rtf.document.RtfPageSetting.rectEquals(RtfPageSetting.java:433)
         at com.lowagie.text.rtf.document.RtfPageSetting.guessFormat(RtfPageSetting.java:362)
         at com.lowagie.text.rtf.document.RtfPageSetting.setPageSize(RtfPageSetting.java:341)
         at com.lowagie.text.rtf.RtfWriter2.setPageSize(RtfWriter2.java:248)
         at com.lowagie.text.Document.open(Unknown Source)
         at view.RTF3.main(RTF3.java:23)
    CAN you HELP me?

    import com.lowagie.text.Document;
    import com.lowagie.text.rtf.parser.RtfParser;
    import java.io.FileInputStream;
    String inputFile = "sample.rtf";
    Document document = new Document();
    document.open();
    RtfParser parser = new RtfParser(null);
    parser.convertRtfDocument(new FileInputStream(inputFile), document);

  • How to read Excel file in flex

    Hi,
         I am new to Adobe flex and i dont know how to read Excel in flex and i need coding for that. So anybody help me...
    thanks in advance...

    Hi
    You can read and parse XLS files (only works with xls-files) with urlloader and a ZIP-lib that can read zip-files.
    public function loadXLS(url:String):void
                var urlLoader:URLLoader = new URLLoader();
                urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
                urlLoader.addEventListener(Event.COMPLETE, onLoadComplete);
                urlLoader.load(new URLRequest(url));
            private function onLoadComplete(even:Event):void
                urlLoader.removeEventListener(Event.COMPLETE, onLoadComplete);
                model.sheetsDict = new Dictionary();
                var zipFile:ZipFile = new ZipFile(urlLoader.data);
                for(var i:int = 0; i < zipFile.entries.length; i++)
                    var entry:ZipEntry = zipFile.entries[i];
                    var data:ByteArray = zipFile.getInput(entry);
                    if(useFile(entry.name, "/sheet([^$]+)"))
                        model.sheetsDict[entry.name.split("xl/")[1]] = new XML(data.toString());
                    else if( useFile(entry.name, "/sharedStrings.xml") )
                        model.sharedStrings = new XML(data.toString());
                    else if( useFile(entry.name, "/workbook.xml$") )
                        model.workbook = new XML(data.toString());
                    else if( useFile(entry.name, "/workbook.xml.rels") )
                        model.rels = new XML(data.toString());
                trace(model.sharedStrings)
    to read the xml properly you have to use namespaces in the reader-class
    namespace ns1 = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
            use namespace ns1;
            namespace ns2 = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
            use namespace ns2;
            namespace ns3 = "http://schemas.openxmlformats.org/markup-compatibility/2006";
            use namespace ns3;
            namespace ns4 = "urn:schemas-microsoft-com:mac:vml";
            use namespace ns4;
            namespace ns5 = "http://schemas.openxmlformats.org/package/2006/relationships";
            use namespace ns5;
    //Olof

  • How to read pdf files using java.io package classes

    Dear All,
    I have a certain requirement that i should read and write PDF files at runtime. With normal java file IO reading is not working. Can any one suggest me how to proceed probably with sample code block
    Thanks in advance.

    hi I also have the pbm. to read pdf file using JAVA
    can any body help meWhy is it so difficult to read the thread you posted in? They say: java.io is pointless, use iText. So why don't you?
    or also I want to read a binary encoded data into
    ascii,
    can anybody give me a hint how to do it.Depends on what you mean with "binary encoding". ASCII's binary encoding, too, basically.

  • Reading Excel files in Java --

    Hi,
    I am trying to read an excel file from Java. It only reads the column, but I want to print the rows, which intersect with the SQL query. The following source displays only values of a column. No problem, but I would like to see the corresponding row numbers or simply number of rows. Can anyone suggest me what to do ASAP?
    Thanks,
    Gunter
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class ExcelReadTest1{
    public static void main(String[] args){
    Connection connection = null;
    try{
    //Vector vector = new Vector();
    String myString="";
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection( "jdbc dbc ata-list" );
    Statement st = con.createStatement();
    ResultSet rs = st.executeQuery( "Select caseid from [sa3$] where iSchool=2" );
    //ResultSet rs = st.executeQuery( "Select * from [Sheet1$]" );
    ResultSetMetaData rsmd = rs.getMetaData();
    int numberOfColumns = rsmd.getColumnCount();
    int row_num=1;
    while ((rs !=null) && rs.next()) {
    myString += "\n Row " + row_num++ + " ";
    for (int i = 1; i <= numberOfColumns; i++)
    //myString += "\n " + rsmd.getColumnName(i);
    myString += " : " + rs.getString(i);
    System.out.println(myString);
    if (i >1)
    System.out.print(", ");
    String columnValue = rs.getString(i);
    System.out.print(" " + columnValue);
    System.out.println("");
    st.close();
    con.close();
    } catch(Exception ex) {
    System.err.print("Exception: ");
    System.err.println(ex.getMessage());

    I took your code and reworked it to access a little database I keep of students at a small private school where my wife works. The Student table has columns "studentID", "firstname", "lastname", and "gradyear".
    Running your code for the output got the following. I cut and pasted the output after it had run through the first 4 students, so you can see what it's doing.
    Row 1 : 1
    1
    Row 1 : 1 : Audrey
    , Audrey
    Row 1 : 1 : Audrey : Budington
    , Budington
    Row 1 : 1 : Audrey : Budington : 2015
    , 2015
    Row 1 : 1 : Audrey : Budington : 2015
    Row 2 : 2
    2
    Row 1 : 1 : Audrey : Budington : 2015
    Row 2 : 2 : Cecilia
    , Cecilia
    Row 1 : 1 : Audrey : Budington : 2015
    Row 2 : 2 : Cecilia : DeRigo
    , DeRigo
    Row 1 : 1 : Audrey : Budington : 2015
    Row 2 : 2 : Cecilia : DeRigo : 2015
    , 2015
    Row 1 : 1 : Audrey : Budington : 2015
    Row 2 : 2 : Cecilia : DeRigo : 2015
    Row 3 : 3
    3
    Row 1 : 1 : Audrey : Budington : 2015
    Row 2 : 2 : Cecilia : DeRigo : 2015
    Row 3 : 3 : Serena
    , Serena
    Row 1 : 1 : Audrey : Budington : 2015
    Row 2 : 2 : Cecilia : DeRigo : 2015
    Row 3 : 3 : Serena : Downes
    , Downes
    Row 1 : 1 : Audrey : Budington : 2015
    Row 2 : 2 : Cecilia : DeRigo : 2015
    Row 3 : 3 : Serena : Downes : 2015
    , 2015
    Row 1 : 1 : Audrey : Budington : 2015
    Row 2 : 2 : Cecilia : DeRigo : 2015
    Row 3 : 3 : Serena : Downes : 2015
    Row 4 : 4
    4
    Row 1 : 1 : Audrey : Budington : 2015
    Row 2 : 2 : Cecilia : DeRigo : 2015
    Row 3 : 3 : Serena : Downes : 2015
    Row 4 : 4 : Dylan
    , Dylan
    Row 1 : 1 : Audrey : Budington : 2015
    Row 2 : 2 : Cecilia : DeRigo : 2015
    Row 3 : 3 : Serena : Downes : 2015
    Row 4 : 4 : Dylan : Gellert
    , Gellert
    Row 1 : 1 : Audrey : Budington : 2015
    Row 2 : 2 : Cecilia : DeRigo : 2015
    Row 3 : 3 : Serena : Downes : 2015
    Row 4 : 4 : Dylan : Gellert : 2015
    , 2015
    You need to figure out the flow of the thing and your println() calls and your looping. Eventually if you straighten it out you will get something like
    Row 1 : 1 : Audrey : Budington : 2015
    Row 2 : 2 : Cecilia : DeRigo : 2015
    Row 3 : 3 : Serena : Downes : 2015
    Row 4 : 4 : Dylan : Gellert : 2015
    Row 5 : 5 : Benjamin : Miller : 2015
    Row 6 : 6 : Timothy : Bolan : 2014
    Row 7 : 7 : Javin : deMello-Folsom : 2014
    Row 8 : 8 : Elizabeth : Eppolito : 2014
    Row 9 : 9 : Harrison : Evans : 2014
    Row 10 : 10 : Emily : Fay : 2014
    *** etc***
    which is what you want, isn't it?

  • How to read excel file in document library and store excel content in sql table

    Hello,
    Can anyone help me how to read the excel file present in document library and store the content inside excel into sql table?
    Please let me know the ways to acheive this. Feel free to give your suggestions.
    Thanks,
    Cool Developer

    Hi!
    this code i have written becuase i donot find any soltions on net for this , u can try with this . :)
    System.Data.OleDb.
    OleDbConnection ExcelConnection = null;
    FileMode fileMode;
    string filePath = ConfigurationManager.AppSettings["TempLoaction"] + "\\" + fileName;
    using (SPSite _site = new SPSite(SPContext.Current.Web.Url))
    using (SPWeb _web = _site.OpenWeb())
    string docLibrary = ConfigurationManager.AppSettings["DocumentLibrary"];
    SPFile _file = _web.GetFile("/" + docLibrary + "/" + fileName);
    fileMode =
    FileMode.Create;
    byte[] byteArray = _file.OpenBinary();
    MemoryStream dataStream = new MemoryStream(byteArray);
    Stream stream = dataStream;
    using (FileStream fs = File.Open(filePath, fileMode))
    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
    fs.Write(buffer, 0, bytesRead);
    fs.Close();
    //Create the Connection String
    try
    string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;
    Data Source ='"
    + filePath + "'; Extended Properties=Excel 5.0";
    //Create the connection
    ExcelConnection =
    new System.Data.OleDb.OleDbConnection(ConnectionString);
    //create a string for the query
    string ExcelQuery;
    //Sheet1 is the sheet name
    //create the query:
    //read columns from the Excel file
    ExcelQuery =
    "Select * from [Sheet1$]"; // from Sheet1";
    //use "Select * ... " to select the entire sheet
    //create the command
    System.Data.OleDb.
    OleDbCommand ExcelCommand = new System.Data.OleDb.OleDbCommand(ExcelQuery, ExcelConnection);
    //Open the connection
    ExcelConnection.Open();
    //Create a reader
    System.Data.OleDb.
    OleDbDataReader ExcelReader;
    ExcelReader = ExcelCommand.ExecuteReader();
    //For each row after the first
    while (ExcelReader.Read())
    thanks,
    kshitij

  • How to read SGML files using Java

    I've got a text categorisation test collection called Reuters-21578 for my Information Retrieval project. It is distributed in 22 files. Each of the first 21 files (reut2-000.sgm through reut2-020.sgm) contains 1000 documents, while the last (reut2-021.sgm) contains 578 documents. The files are in SGML format. Each of the 22 files begins with a document type declaration line:
    <!DOCTYPE lewis SYSTEM "lewis.dtd"> The DTD file lewis.dtd is included in the distribution. Following the document type declaration line are individual Reuters articles marked up with SGML tags.
    My questions is how to write a java program to read those 21578 documents or transform them into 21578 seperated text files.

    I guess I missed something. What is Renes link?. The
    parser stuff isn't really what I'm looking for. I'm
    a new at and just learning java and I just want to
    know the easiest way to read a SGML file. Should I
    use a buffered Reader with a Pushback Input Stream?Hang on.....you want to just read the file without intelligently extracting the SGML data contained within and so have no need of a parser?
    Well, in that case, its just text.....so just use BufferedReader or whatever to read the text data. If I understand you correctly, all you really wanted to ask was "how do I read a text file?"

  • How to read XML files from java

    i need a sugession that how to read a xml file using java code
    and i need to parse using some parsers and display attributes and entity seperately
    as a string.......

    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.io.SAXReader;
    import java.io.File;
    import java.text.AttributedCharacterIterator.Attribute;
    import java.util.Iterator;
    import java.util.StringTokenizer;
    public class XmlParser
    private String Result="";
    private String Final="";
    private String Delim="";
    public void bar1(Document document) throws DocumentException
    org.dom4j.Element root = document.getRootElement();
    // System.out.println(root.getName());
    bar2(root);
    System.out.println(this.Result);
    process();
    public void bar2(org.dom4j.Element e)
    for(Iterator i = e.elementIterator();i.hasNext();)
    org.dom4j.Element Element = (org.dom4j.Element) i.next();
    Result += Element.getName()+"\t"+Element.getText()+"\n";
    bar2(Element);
    public void process()
    StringTokenizer Tokenizer = new StringTokenizer(this.Result,"\n");
    String element;
    while(Tokenizer.hasMoreTokens())
    element = Tokenizer.nextToken();
    StringTokenizer Tokenizer2 = new StringTokenizer(element,"\t");
    // Do what ever String Process here Example
    this.Final += element.getName();
    this.Final += this.Delim;
    System.out.println(this.Final);
    public static void main(String s[])throws Exception
    Document document = null;
    SAXReader reader = new SAXReader();
    File f1= new File("D:/Rajesh/EDI to XML/EDI.xml");
    document = reader.read(f1);
    Demo obj = new Demo();
    obj.bar1(document);
    i think this will hep full.......

  • How to read word files using java

    Reding text files is prity simple. But when i tried to read msword file I could do it.
    Can any one discuss how to do it
    Thanks

    Sorry this is not a reply but in fact i need the solution for that as i am in an urgency of that can you post that to to me if u have got it, I need it for my project

  • How to print  Excel file in java?

    Hi, all
    I had written a program to generate a Report with Excel in java using the jexcelapi_2_5_7 . But I don't know how to print it in java program. It seems that java print Service don�t support Excel flavor. How should I do? It will be a great appreciate for me if anyone could help me.
    Regards
    David

    Hi ,
    i m asking if you got a solution for your problem ;
    i need solution to the same problem
    thx in advance

  • Reading PDF files in java

    Hi,
    can any one help me on how to read pdf files in java using itext. I have written some piece of code but it is of no use. It is giving some garbage.
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import com.lowagie.text.pdf.PdfReader;
    public class PdfAccess
    public static void main(String[] args)
    try {
    String pdfFile = args[0];
    PdfReader reader = new PdfReader(pdfFile);
    int pageCount = reader.getNumberOfPages();
    System.out.println(pageCount);
    String content = " ";
    for(int i=1;i<=pageCount;i++) {
    byte[] pageContent = reader.getPageContent(i);
    content = content+(pageContent.toString());
    System.out.println(content.trim());
    } catch(Exception e) { }
    can any one help me on how to get contents of the file. Are there examples avalilable??

    * Try this by PDFBOX , it will execute well as per ur request..........
        public void getPdfText(String fileName) throws IOException {
            StringWriter sw = new StringWriter();
            PDDocument doc = null;
            try {
                doc = PDDocument.load(fileName);
                PDFTextStripper stripper = new PDFTextStripper();
                stripper.setStartPage(1);
                stripper.setEndPage(Integer.MAX_VALUE);
                stripper.writeText(doc, sw);
                OutputStream out=new FileOutputStream(new File("d://PDFText.txt"));
                PrintStream write=new PrintStream(out,true,"UTF-8");
                write.print(sw.toString());
                //System.out.println(sw.toString());
            } finally {
                if (doc != null) {
                    doc.close();
    Can..Can...If we Try...!

  • How to Read excel or .csv files in java

    I am writing a program which takes input as excel or .csv file.
    How to read these files.
    Any API's are existed or need to use the third party jar.
    Please suggest me.
    Thanks & Regards

    Did you search in google? Did you search here? There are so many excel related questions here, including answers about third party libraries.
    I have the impression that you didn't research at all.
    _[How to ask questions|http://faq.javaranch.com/view?HowToAskQuestionsOnJavaRanch]_ It's the same here.

  • How to save html as Excel file im java

    Hi to all
    How can i save html file as Excel file in Java
    If any solutions plz help Me

    Thanks for ur reply
    Source URL is::http://www.sttpc.com/reseller/price.htm
    Target is to save table data into Excel Sheet.
    Upto saving that file as Excel file its working (using I/O).
    When iam trying to read excel sheet data then iam getting OLE Exception.
    plz suggest me other Alternate solutions to overcome this problem.
    I tried htmlparser from sourceforge.net i got partial ouput.But i want dynamic solution.
    Thanks.

  • How to compare two excel files in java ?

    how do i compare two excel files in java.?
    I have two excel files stored on my computer in d: drive.
    Ex:
    D:\\file a
    D:\\file b
    How to compare the contents of these two files and print " files are equal " or "files not equal "

    Javamastermahe wrote:
    I mean i want to print on the console "files are equal " or any message like " both the files match "If this is your requirement, this program satisfies it...
    import java.util.Random;
    public class SuperExcelTester {
        public static void main(String[] args) {
            Random rnd = new Random();
            String[] messages = {
                "files are equal",
                "files are not equal",
                "unexpected error"
            int index = rnd.nextInt(messages.length);
            System.out.println(messages[index]);
    }

  • How do I produce an excel file using java code

    How do i produce an excel file using java code.
    If it is possible would ne one have ne source code as an example.
    I have tried looking up information on outputing the information to a *.csv file but unfortunality i have had no luck in finding any information. To be exact ne source code.
    Thanks
    Lee

    That's what I use and I'd be the first to admit that it's very messy. But it works. Go use Google and see what else you can find.

Maybe you are looking for

  • Why does my airplay icon keep disappearing from my ipad?

    Airplay icon is very unstable. I have tried all suggested remedies. Restarting router makes it appear but then it goes off again after a short time. Sick of resetting router - everything else works fine - this happens simultaneously on both our iPads

  • About Idoc sender

    Why we don't give CC and adapter for sender Idoc and HTTPs ? I know that two are in ABAP stack, then how to communicate that and where the XML conversion done at ABAP sys or XI server or conversion not required ?

  • Landscape Paper Layout - Won't Display on the Web

    I am trying to display a report (paper layout only) on the web using desformat=pdf. To test if the report could be viewed via the web, I created a simple version and could view it in my browser w/ no problem; however, after adding some columns and ma

  • Robohelp PDF issues

    Hello All, I am using Robohelp 9 to generate PDF output. I have used used List Styles extensively in my project.However, when I generate PDF output list styles are not getting aligned properly. Please assist. Thanks, Panendra P.

  • "Creating ASInstance" while OBIEE Installation failed !!

    Hello Gurus, While installing OBIEE 11g on Windows 7 64 bit, I am getting AS instance in configuration is getting failed !! Here is the log.... [2013-02-06T21:37:25.356+05:30] [as] [NOTIFICATION] [] [oracle.as.provisioning] [tid: 24] [ecid: 0000JmkAX