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 "";
        }
    }
}
复制代码

 

posted @   hjhsysu  阅读(1947)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示