java中使用jxl读取excel中的数据

package bboss;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
/**
 * 
 * @author llh
 *
 */
public class ExcelReadSOAP {
    /**
     * 使用jxl读取excel中数据
     * 
     * @param args
     * @throws IOException
     * @throws BiffException
     */
    public static String ExcelReadSOAP(String code) throws IOException, BiffException {
        int lie = 0;
        String retur = null;
        System.out.println("项目路径" + System.getProperty("user.dir"));
        File file = new File(System.getProperty("user.dir") + "\\case\\编码大全.xls");
        System.out.println("文件路径:" + file + "\n" + "文件绝对路径:" + file.getAbsolutePath());
        // 读取xls文件流
        InputStream is = new FileInputStream(file.getAbsolutePath());
        // 使用jxl
        Workbook rwb = Workbook.getWorkbook(is);
        // 获取当前excel中共有几个表
        Sheet[] sheets = rwb.getSheets();
        // 获取表数
        int pages = sheets.length;
        System.out.println("表数:" + pages);
        for (int i = 0; i < pages; i++) {
            Sheet sheet = sheets[i];
            // 有多少列
            int cols = sheet.getColumns();
            System.out.println("有" + cols + "列");
            // 有多少行
            int rows = sheet.getRows();
            System.out.println("有" + rows + "行");
            // 列循环
            for (int j = 0; j < cols; j++) {
                //行循环
                for(int k = 0 ; k <rows ; k++){
                    //定位坐标,从(0,0开始)
                    Cell excelRows = sheet.getCell(j, k);
                    //取坐标值
                    String e = excelRows.getContents();
                    //如果找到相应的交易编码,保存所在列值
                    if(code.equals(e)){
                        lie = j;
                    }
                }
            }
            //取出对应交易编码的头部信息并返回
            retur = sheet.getCell(lie,0).getContents();
            if(retur==null){
                System.out.println("-----------在对应协议模板中未找到相对应的业务-----------");
            }
        }
        return retur;

    }

}

在项目中,我们经常会使用到excel来保存一些数据,所以在项目中,读取excel中的内容也成为了我们必须要经常使用到的技术,在这里做一下记录,为了方便自己随时查看,也为了帮助大家需要这个方法的来借鉴。

猜你喜欢

转载自www.cnblogs.com/javallh/p/8919008.html