如何使用Java 8将Excel作为数据库访问

时间:2022-09-27 13:49:47

I am using Java 8.

我使用的是Java 8。

When i am trying to access Excel data(basically this is my test data) through jdbc-odbc, i am getting "java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver"

当我试图通过jdbc-odbc访问Excel数据(基本上这是我的测试数据)时,我得到“java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver”

And also i am trying to access data as non DSN.

而且我也试图以非DSN的形式访问数据。

I surfed net and came to know that Oracle deprecated support to jdbc-odbc.

我浏览网络并且知道Oracle不赞成对jdbc-odbc的支持。

So what is the easiest way to access this Excel data using Java?

那么使用Java访问这些Excel数据的最简单方法是什么?

Connection con=null;
    Statement stmt=null;
    ResultSet rs=null;
    String query = "select TestScript from [TS 360 Scripts$]";

    try
    {
        Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
        con = DriverManager.getConnection("jdbc:odbc:;Driver={Microsoft Excel Driver(*.xlsx)};DBQ=D://TS 360 Script with Count.xlsx");


        stmt=con.createStatement();
        rs=stmt.executeQuery(query);
        while(rs.next())
        {
            System.out.println(rs.getString("TestScript"));
        }

        con.close();
        rs.close();
        stmt.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

3 个解决方案

#1


1  

This might be a little late but in case you still have the issue you can retain access excel as a db with java 8 using Fillo: http://codoid.com/fillo/

这可能有点晚了但是如果你仍然遇到问题,你可以使用Fillo保留访问excel作为带有java 8的数据库:http://codoid.com/fillo/

#2


0  

Uday- you can easily do whatever you want to do with Apache POI jar

Uday-你可以轻松地用Apache POI jar做任何你想做的事情

As Your are mentioned your requirement: of all rows having isExecuted String Yes. I tried with this jar.

正如您所提到的那样:所有具有isExecuted字符串的行是的。我试着用这个罐子。

Try this

package com.dd.selenium;

import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class PerformDDTest {

    private static HSSFWorkbook xlWBook;
    private static HSSFSheet xlSheet;
    private static HSSFRow xlRow;
    private static HSSFCell xlCell;
    private static String filePath = "/home/dinesh/";
    private static String fileName = "test.xls";

    public static void main(String[] args) throws InterruptedException {

        try {

            FileInputStream xlFile = new FileInputStream(filePath + fileName);

            // Access the required test data sheet

            xlWBook = new HSSFWorkbook(xlFile);

            // Assuming your data is in Sheet1- if not use your own sheet name
            xlSheet = xlWBook.getSheet("Sheet1");

            // gives row count in sheet
            int noOfRows = xlSheet.getPhysicalNumberOfRows();

            // gives column count in sheet
            xlRow = xlSheet.getRow(0);
            int noOfColumns = xlRow.getLastCellNum();

            // excelData - 2 dimm array - stores all the excel data -Sheet1 only
            String[][] excelData = new String[noOfRows][noOfColumns];

            // r - row c- column
            for (int r = 1; r < noOfRows; r++) {
                for (int c = 0; c < noOfColumns; c++) {
                    xlRow = xlSheet.getRow(r);
                    xlCell = xlRow.getCell(c);

                    // Here we have complete excel data in an array -excelData-

                    excelData[r][c] = xlCell.getStringCellValue();

                    // System.out.println("row: " + r + " column: " + c);
                    // System.out.println(excelData[r][c]);
                }
            }

            // creating an array to store isExected column
            String[][] isExecuted = new String[noOfRows][1];

            for (int row = 1; row < noOfRows; row++) {
                // here column is always only one
                // so c=0

                // extracting a isExecuted column - and considering it as last
                // column in sheet
                // in your case it is not then - count the column position : use
                // position-1
                // ex: if column position is 7 then use 6 as below
                // isExecuted[row][0]= excelData[row][6];

                isExecuted[row][0] = excelData[row][noOfColumns - 1];

                if (isExecuted[row][0].equalsIgnoreCase("yes")) {

                    // accessing complete row -which isExecuted=Yes

                    // *********IMPORTANT*****
                    for (int col = 0; col < noOfColumns; col++) {
                        // prints all the rows where isExecuted column has Yes
                        System.out.println(excelData[row][col]);
                    }
                }

                // System.out.println(isExecuted[row][0]);

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

I used this Excel Data:

我用过这个Excel数据:

Test Case Name  Username    Password    Results IsExecute
APACHE_POI_TC   testuser_1  Test@123    Pass    Yes
APACHE_POI_TC   testuser_2  Test@124    Pass    No
APACHE_POI_TC   testuser_3  Test@125    Pass    Yes
APACHE_POI_TC   testuser_4  Test@126    Pass    Yes
APACHE_POI_TC   testuser_5  Test@127    Pass    No
APACHE_POI_TC   testuser_6  Test@128    Pass    Yes

#3


0  

Dont Access Excel file as a database. Instead use a jar such as Apache POI For Microsoft Documents

不要将Excel文件作为数据库访问。而是使用诸如Apache POI For Microsoft Documents之类的jar

Download Link: Apache POI For MS Docs- Jar

下载链接:Apache POI For MS Docs-Jar

An Example For using this API:

示例使用此API:

Note: you must add apache poi jar to your build path before running it

注意:在运行之前,必须将apache poi jar添加到构建路径中

package com.dd.selenium;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;


public class PerformDDTest {

    private static HSSFWorkbook xlWBook;

    private static HSSFSheet xlSheet;

    private static HSSFRow xlRow;

    private static HSSFCell xlCell;

    private static String filePath = "/home/dinesh/";

    private static String fileName = "test.xls";

    private static String url = "http://store.demoqa.com/"; 

    private static String result = "Pass";


    public static void main(String[] args) throws InterruptedException {

        try {
            FileInputStream xlFile = 
                    new FileInputStream(filePath+fileName);

            //Access the required test data sheet

            xlWBook =  new HSSFWorkbook(xlFile);

            xlSheet = xlWBook.getSheet("Sheet1");

            xlRow = xlSheet.getRow(1);

            String username = xlRow.getCell(1).getStringCellValue();
            String password = xlRow.getCell(2).getStringCellValue();

            FirefoxDriver driver = new FirefoxDriver();

            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

            driver.manage().window().maximize();


            driver.get(url);

            driver.findElement(By.xpath(".//*[@id='account']/a")).click();

            driver.findElement(By.id("log")).sendKeys(username);
            driver.findElement(By.id("pwd")).sendKeys(password);

            driver.findElement(By.id("login")).click();



            driver.findElement(By.xpath(".//*[@id='account_logout']/a")).click();

            Thread.sleep(5000);

            driver.quit();

            setResultCell();


            FileOutputStream fout = new FileOutputStream(filePath+fileName);

            xlWBook.write(fout);

            fout.flush();
            fout.close();



        } catch (IOException e) {
            // TODO Auto-generated catch block
            result = "Failed";
            setResultCell();
            e.printStackTrace();
        }



    }


    private static void setResultCell() {
        xlCell = xlRow.getCell(3, xlRow.RETURN_BLANK_AS_NULL);

        if(xlCell == null ){
            xlCell = xlRow.createCell(3);
            xlCell.setCellValue(result);
        }else{
            xlCell.setCellValue(result);
        }
    }

}

#1


1  

This might be a little late but in case you still have the issue you can retain access excel as a db with java 8 using Fillo: http://codoid.com/fillo/

这可能有点晚了但是如果你仍然遇到问题,你可以使用Fillo保留访问excel作为带有java 8的数据库:http://codoid.com/fillo/

#2


0  

Uday- you can easily do whatever you want to do with Apache POI jar

Uday-你可以轻松地用Apache POI jar做任何你想做的事情

As Your are mentioned your requirement: of all rows having isExecuted String Yes. I tried with this jar.

正如您所提到的那样:所有具有isExecuted字符串的行是的。我试着用这个罐子。

Try this

package com.dd.selenium;

import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class PerformDDTest {

    private static HSSFWorkbook xlWBook;
    private static HSSFSheet xlSheet;
    private static HSSFRow xlRow;
    private static HSSFCell xlCell;
    private static String filePath = "/home/dinesh/";
    private static String fileName = "test.xls";

    public static void main(String[] args) throws InterruptedException {

        try {

            FileInputStream xlFile = new FileInputStream(filePath + fileName);

            // Access the required test data sheet

            xlWBook = new HSSFWorkbook(xlFile);

            // Assuming your data is in Sheet1- if not use your own sheet name
            xlSheet = xlWBook.getSheet("Sheet1");

            // gives row count in sheet
            int noOfRows = xlSheet.getPhysicalNumberOfRows();

            // gives column count in sheet
            xlRow = xlSheet.getRow(0);
            int noOfColumns = xlRow.getLastCellNum();

            // excelData - 2 dimm array - stores all the excel data -Sheet1 only
            String[][] excelData = new String[noOfRows][noOfColumns];

            // r - row c- column
            for (int r = 1; r < noOfRows; r++) {
                for (int c = 0; c < noOfColumns; c++) {
                    xlRow = xlSheet.getRow(r);
                    xlCell = xlRow.getCell(c);

                    // Here we have complete excel data in an array -excelData-

                    excelData[r][c] = xlCell.getStringCellValue();

                    // System.out.println("row: " + r + " column: " + c);
                    // System.out.println(excelData[r][c]);
                }
            }

            // creating an array to store isExected column
            String[][] isExecuted = new String[noOfRows][1];

            for (int row = 1; row < noOfRows; row++) {
                // here column is always only one
                // so c=0

                // extracting a isExecuted column - and considering it as last
                // column in sheet
                // in your case it is not then - count the column position : use
                // position-1
                // ex: if column position is 7 then use 6 as below
                // isExecuted[row][0]= excelData[row][6];

                isExecuted[row][0] = excelData[row][noOfColumns - 1];

                if (isExecuted[row][0].equalsIgnoreCase("yes")) {

                    // accessing complete row -which isExecuted=Yes

                    // *********IMPORTANT*****
                    for (int col = 0; col < noOfColumns; col++) {
                        // prints all the rows where isExecuted column has Yes
                        System.out.println(excelData[row][col]);
                    }
                }

                // System.out.println(isExecuted[row][0]);

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

I used this Excel Data:

我用过这个Excel数据:

Test Case Name  Username    Password    Results IsExecute
APACHE_POI_TC   testuser_1  Test@123    Pass    Yes
APACHE_POI_TC   testuser_2  Test@124    Pass    No
APACHE_POI_TC   testuser_3  Test@125    Pass    Yes
APACHE_POI_TC   testuser_4  Test@126    Pass    Yes
APACHE_POI_TC   testuser_5  Test@127    Pass    No
APACHE_POI_TC   testuser_6  Test@128    Pass    Yes

#3


0  

Dont Access Excel file as a database. Instead use a jar such as Apache POI For Microsoft Documents

不要将Excel文件作为数据库访问。而是使用诸如Apache POI For Microsoft Documents之类的jar

Download Link: Apache POI For MS Docs- Jar

下载链接:Apache POI For MS Docs-Jar

An Example For using this API:

示例使用此API:

Note: you must add apache poi jar to your build path before running it

注意:在运行之前,必须将apache poi jar添加到构建路径中

package com.dd.selenium;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;


public class PerformDDTest {

    private static HSSFWorkbook xlWBook;

    private static HSSFSheet xlSheet;

    private static HSSFRow xlRow;

    private static HSSFCell xlCell;

    private static String filePath = "/home/dinesh/";

    private static String fileName = "test.xls";

    private static String url = "http://store.demoqa.com/"; 

    private static String result = "Pass";


    public static void main(String[] args) throws InterruptedException {

        try {
            FileInputStream xlFile = 
                    new FileInputStream(filePath+fileName);

            //Access the required test data sheet

            xlWBook =  new HSSFWorkbook(xlFile);

            xlSheet = xlWBook.getSheet("Sheet1");

            xlRow = xlSheet.getRow(1);

            String username = xlRow.getCell(1).getStringCellValue();
            String password = xlRow.getCell(2).getStringCellValue();

            FirefoxDriver driver = new FirefoxDriver();

            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

            driver.manage().window().maximize();


            driver.get(url);

            driver.findElement(By.xpath(".//*[@id='account']/a")).click();

            driver.findElement(By.id("log")).sendKeys(username);
            driver.findElement(By.id("pwd")).sendKeys(password);

            driver.findElement(By.id("login")).click();



            driver.findElement(By.xpath(".//*[@id='account_logout']/a")).click();

            Thread.sleep(5000);

            driver.quit();

            setResultCell();


            FileOutputStream fout = new FileOutputStream(filePath+fileName);

            xlWBook.write(fout);

            fout.flush();
            fout.close();



        } catch (IOException e) {
            // TODO Auto-generated catch block
            result = "Failed";
            setResultCell();
            e.printStackTrace();
        }



    }


    private static void setResultCell() {
        xlCell = xlRow.getCell(3, xlRow.RETURN_BLANK_AS_NULL);

        if(xlCell == null ){
            xlCell = xlRow.createCell(3);
            xlCell.setCellValue(result);
        }else{
            xlCell.setCellValue(result);
        }
    }

}