javajxl读取excel表格后读取后并用纯数组方式去重但是下标越界

javajxl读取excel表格后读取后并用纯数组方式去重但是下标越界!@#$%^&

数组越界错误通常是由于数组下标超出了数组的长度而引起的。如果使用纯数组方式实现去重操作,可能会出现数组越界的错误。可以采取以下的方式避免这个问题:

获取 Excel 中数据的行数和列数,根据这个行列数创建对应的数组;
在读取 Excel 单元格时,将数据转存到对应的数组中;
在实现去重操作时,使用实际存储的数据长度作为数组长度,而不是 Excel 的行列数作为数组长度;
在数组访问操作时,判断当前下标是否越界。
以下是可能参考的Java代码实现:


import java.io.File;
import java.util.HashSet;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ExcelUtil {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        int row = 0; // Excel行数
        int col = 0; // Excel列数
        String[][] array = null; // 数组
        
        try {
            Workbook book = Workbook.getWorkbook(new File("test.xls")); // 读取Excel
            Sheet sheet = book.getSheet(0); // 获取第一个工作表
            
            row = sheet.getRows();
            col = sheet.getColumns();
            array = new String[row][col]; // 创建对应行列数的数组
            
            // 读取数据存储到数组中
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++) {
                    Cell cell = sheet.getCell(j, i);
                    array[i][j] = cell.getContents();
                }
            }
            
            // 基于数组进行去重操作
            String[] uniqueArray = new String[row * col];
            int uniqueCount = 0;
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++) {
                    if (set.add(array[i][j])) {
                        uniqueArray[uniqueCount] = array[i][j];
                        uniqueCount++;
                    }
                }
            }
            // 输出去重后的数据
            for (int i = 0; i < uniqueCount; i++) {
                System.out.println(uniqueArray[i]);
            }

            book.close();
        } catch (BiffException e) {
            e.printStackTrace();
        } catch