Java——jxl读取Excel文件

1.创建文件流,打开EXCEL文件(jxi不支持.xlsx文件,支持.xls)

FileInputStream excelFile = new FileInputStream(excelPath);
Workbook workbook = Workbook.getWorkbook(excelFile);

2.切换到对应文件名

Sheet excelSheet = workbook.getSheet(sheetName);

3.获取实际行数和列数

int rows = excelSheet.getRows();//行数
Cell[] cell = excelSheet.getRow(0);// 获得第一行的所有单元格
int columnNum = cell.length; // 单元格的个数 值 赋给 列数

4.读取数据

public static String ReadData(Sheet excelSheet, int row, int col){
        try{
            String CellData= "";
            Cell cell = excelSheet.getRow(row)[col];
            CellData = cell.getContents().toString(); 
            return CellData;
        }catch(Exception e){
            return "";
        }
    }

 

示例:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class jxlExcel {
    
    public static void main(String[] args) throws IOException {
        String excelPath = "F:\\login.xls";
        String sheetName = "001";
        try{
            FileInputStream excelFile = new FileInputStream(excelPath);
            Workbook workbook = Workbook.getWorkbook(excelFile);
            Sheet excelSheet = workbook.getSheet(sheetName);
            int rows = excelSheet.getRows();//行数
            Cell[] cell = excelSheet.getRow(0);// 获得第一行的所有单元格
            int columnNum = cell.length; // 单元格的个数 值 赋给 列数
        
            for(int row = 0;row< rows; ++row){
                for (int col =0; col < columnNum; ++col){
                    System.out.print(ReadData(excelSheet, row, col) + ' ');
                    if(col ==1)
                        System.out.println();
                }
            }
            workbook.close();
        }catch (FileNotFoundException e ){
            System.out.println("找不到该文件");
        } catch (BiffException e) {
            e.printStackTrace();
        }
    }
    
    public static String ReadData(Sheet excelSheet, int row, int col){
        try{
            String CellData= "";
            Cell cell = excelSheet.getRow(row)[col];
            CellData = cell.getContents().toString(); 
            return CellData;
        }catch(Exception e){
            return "";
        }
    }
}

 

转载于:https://www.cnblogs.com/hjhsysu/p/5743824.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值