使用java读取Excel表格中的数据 ,解决方案搜集

Java EXCEL API简介 
Java Excel是一开放源码项目,经过它Java开发人员能够读取Excel文件的内容、建立新的Excel文件、更新已经存在的Excel文件。使用该API非Windows操做系统也能够经过纯Java应用来处理Excel数据表。由于是使用Java编写的,因此咱们在Web应用中能够经过JSP、Servlet来调用API实现对Excel数据表的访问。html

应用示例 
从Excel文件读取数据表 

Java Excel API既能够从本地文件系统的一个文件(.xls),也能够从输入流中读取Excel数据表。读取Excel数据表的第一步是建立Workbook(术语:工做薄),下面的代码片断举例说明了应该如何操做:  须要用到一个开源的jar包,jxl.jar。   下载地址java

File file = new File("c:\\a.xls");  
InputStream in = new FileInputStream(file);  
Workbook workbook = Workbook.getWorkbook(in);  
//获取第一张Sheet表  
Sheet sheet = workbook.getSheet(0);  
  
//咱们既可能经过Sheet的名称来访问它,也能够经过下标来访问它。若是经过下标来访问的话,要注意的一点是下标从0开始,就像数组同样。  
//获取第一行,第一列的值   
Cell c00 = rs.getCell(0, 0);   
String strc00 = c00.getContents();   
//获取第一行,第二列的值   
Cell c10 = rs.getCell(1, 0);   
String strc10 = c10.getContents();   
//咱们能够经过指定行和列获得指定的单元格Cell对象  
  Cell cell = sheet.getCell(column, row);  
  //也能够获得某一行或者某一列的全部单元格Cell对象  
  Cell[] cells = sheet.getColumn(column);  
  Cell[] cells2 = sheet.getRow(row);  
  //而后再取每个Cell中的值  
  String content = cell.getContents();

这个jar包中还有不少其余的方法,就须要本身去摸索了。apache

 

===========================================如下为本身调试后的代码数组

1.如图,添加jxl.jar文件ide

建立excelReader类post

package excelReader;

import java.io.*;
import jxl.*;
import jxl.read.biff.BiffException;

public class ExcelReader {
	String path = "C:\\data.xlsx";
	public ExcelReader(String path){
		this.path = path;
	}
	
	public String readExcel(int sheetNum,int col,int row) throws BiffException, IOException{
		File file = new File(path);  
		InputStream in = new FileInputStream(file);  
		Workbook workbook = Workbook.getWorkbook(in);  
		//获取第一张Sheet表  
		Sheet sheet = workbook.getSheet(sheetNum);  
		//咱们既可能经过Sheet的名称来访问它,也能够经过下标来访问它。若是经过下标来访问的话,要注意的一点是下标从0开始,就像数组同样。  
		//获取第一行,第一列的值   
		Cell celV = sheet.getCell(col, row);   
		String strv = celV.getContents();   
		return strv;
	}
	
	public String getValue(int sheetNum,int col,int row) throws BiffException, IOException{
		return readExcel(sheetNum,col,row);
	}
	
}

 

建立Test类测试

import java.io.IOException;
import jxl.read.biff.BiffException;
import com.sun.org.apache.bcel.internal.generic.NEW;
import excelReader.*;


public class Test {
	public static void main(String[] args) throws BiffException, IOException {
		System.out.println(new ExcelReader("C:\\jxlrwtest.xls").getValue(0, 1, 13));//sheet,col,row
	}
}

 

===============================================================================ui

最近作自动化须要从文件读取数据作参数化,网上发现一个不错的解决方案。this

准备:新建一个excel文件,文件名为测试类名,sheet名为测试方法名操作系统

        excel第一行为标题,从第二行开始为测试数据

        build path:jxl.jar

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.testng.Assert;

import jxl.*;

/**
 * Excel放在Data文件夹下</p>
 * Excel命名方式:测试类名.xls</p>
 * Excel的sheet命名方式:测试方法名</p>
 * Excel第一行为Map键值</p>
 * 代码参考郑鸿志的Blog
 * {@link www.zhenghongzhi.cn/post/42.html}
 * @ClassName: ExcelDataProvider
 * @Description: TODO(读取Excel数据)
 */
public class ExcelDataProvider implements Iterator<Object[]> {

    private Workbook book         = null;
    private Sheet    sheet        = null;
    private int      rowNum       = 0;
    private int      currentRowNo = 0;
    private int      columnNum    = 0;
    private String[] columnnName;

    public ExcelDataProvider(String classname, String methodname) {

        try {

            int dotNum = classname.indexOf(".");

            if (dotNum > 0) {
                classname = classname.substring(classname.lastIndexOf(".") + 1,
                        classname.length());
            }
            //从/data文件夹下读取以类名命名的excel文件
            String path = "data/" + classname + ".xls";
            InputStream inputStream = new FileInputStream(path);

            book = Workbook.getWorkbook(inputStream);
            //取sheet
            sheet = book.getSheet(methodname);
            rowNum = sheet.getRows();
            Cell[] cell = sheet.getRow(0);
            columnNum = cell.length;
            columnnName = new String[cell.length];

            for (int i = 0; i < cell.length; i++) {
                columnnName[i] = cell[i].getContents().toString();
            }
            this.currentRowNo++;

        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail("unable to read Excel data");
        }
    }

    public boolean hasNext() {

        if (this.rowNum == 0 || this.currentRowNo >= this.rowNum) {

            try {
                book.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        } else {
            // sheet下一行内容为空断定结束
            if ((sheet.getRow(currentRowNo))[0].getContents().equals(""))
                return false;
            return true;
        }
    }

    public Object[] next() {

        Cell[] c = sheet.getRow(this.currentRowNo);
        Map<String, String> data = new HashMap<String, String>();
        // List<String> list = new ArrayList<String>();

        for (int i = 0; i < this.columnNum; i++) {

            String temp = "";

            try {
                temp = c[i].getContents().toString();
            } catch (ArrayIndexOutOfBoundsException ex) {
                temp = "";
            }

            // if(temp != null&& !temp.equals(""))
            // list.add(temp);
            data.put(this.columnnName[i], temp);
        }
        Object object[] = new Object[1];
        object[0] = data;
        this.currentRowNo++;
        return object;
    }

    public void remove() {
        throw new UnsupportedOperationException("remove unsupported.");
    }
}
相关文章
相关标签/搜索