首页 > 技术文章 > JAVA中读取xls数据方法介绍

HCT118 2015-05-17 13:36 原文

下面是xls中的数据内容:
用例编号
(UI-0001)
用例名称
({验证页面跳转|验证元素文本}-简要明确表述)
验证类型 是否执行 初始URL 初始元素xpath 目标元素xpath 目标元素属性 期望结果
UI-0001 验证页面跳转-登录 当前标签页 执行 http://www.yixun.com/ //a[@id='j_login'] 0 0 https://base.yixun.com/login.html
UI-0002 验证页面跳转-购物车 当前标签页 执行 http://www.yixun.com/ //a[contains(span, '购物车')]/span 0 0 http://buy.yixun.com/showcart.html

 使用Java读取上面的内容,所用的jar包为poi-3.11-20141221.jar下载地址如下:

http://poi.apache.org/download.html

package baidu;

import java.io.FileInputStream;

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 ExcelRead 
{
    public String getValues(String filePath ) 
    {
        int a=0;
        String values = null;
        try{
                // 创建对Excel工作簿文件的引用
                HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(filePath));
                // 创建对工作表的引用。
                // 本例是按名引用(让我们假定那张表有着缺省名"Sheet1")
                HSSFSheet sheet = workbook.getSheet("Sheet1");
                // 也可用getSheetAt(int index)按索引引用,
                // 在Excel文档中,第一张工作表的缺省索引是0,
                // 其语句为:HSSFSheet sheet = workbook.getSheetAt(0);
                // 读取左上端单元
                 a=sheet.getLastRowNum();
                System.out.println(a);
                for(int j=1;j<=a;j++)
                {
                    HSSFRow row = sheet.getRow(j);
                    System.out.println("-----------------------第"+j+"行数据----------------");
                    for(int i = 0;i<row.getLastCellNum();i++)
                    {
                        HSSFCell cell = row.getCell(i);
                      //输出单元内容,cell.getStringCellValue()就是取所在单元的值
                        values = cell.getStringCellValue();
                        System.out.println("单元格内容是: " + values); 
                    }
                }
            }catch(Exception e) {
                System.out.println("已运行xlRead() : " + e );
            }
        return values;
    }
    public static void main(String args[]) 
    {
        String filePath="E:\\TestPageCjtvPara.xls";
        ExcelRead er = new ExcelRead();
        er.getValues(filePath);
    }
}

 输出结果:

2
-----------------------第1行数据----------------
单元格内容是: UI-0001
单元格内容是: 验证页面跳转-登录
单元格内容是: 当前标签页
单元格内容是: 执行
单元格内容是: http://www.yixun.com/
单元格内容是: //a[@id='j_login']
单元格内容是: 0
单元格内容是: 0
单元格内容是: https://base.yixun.com/login.html
-----------------------第2行数据----------------
单元格内容是: UI-0002
单元格内容是: 验证页面跳转-购物车
单元格内容是: 当前标签页
单元格内容是: 执行
单元格内容是: http://www.yixun.com/
单元格内容是: //a[contains(span, '购物车')]/span
单元格内容是: 0
单元格内容是: 0
单元格内容是: http://buy.yixun.com/showcart.html

 

推荐阅读