zoukankan      html  css  js  c++  java
  • 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 "";
            }
        }
    }
  • 相关阅读:
    拷贝构造函数的用法
    虚基类的用法
    函数模板的用法,以及类外定义的注意事项
    怎么学好python?
    树状数组单点更新和区间查询
    线段树的基本操作
    快排算法的实现
    react-redux 中 connect 的常用写法
    ant-design表单处理和常用方法及自定义验证
    ionic 签名、打包
  • 原文地址:https://www.cnblogs.com/hjhsysu/p/5743824.html
Copyright © 2011-2022 走看看