You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何从Excel表格中读取随机单元格数据

实现方案

核心逻辑是先把固定列的姓名数据缓存到两个独立列表,再通过随机索引取值:

  • 读取工作表时,将第一列的名存入List<String> firstNameList,第二列的姓存入List<String> lastNameList
  • 生成范围为[0, 列表长度-1]的随机整数作为索引,分别从两个列表中取出元素拼接即可得到随机姓名

注意:姓名列表仅需加载一次缓存即可,无需每次调用随机方法都重新读取Excel,可大幅提升调用性能

代码示例

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;

// 全局缓存姓名列表
private List<String> firstNameList = new ArrayList<>();
private List<String> lastNameList = new ArrayList<>();
private Random random = new Random();

// 加载Excel数据到缓存,初始化时调用一次即可
public void loadNameData(String sheetName) {
    int index = workbook.getSheetIndex(sheetName);
    XSSFSheet sheet = workbook.getSheetAt(index);
    // 有表头则将i初始值改为1,跳过表头行
    for (int i = 0; i <= sheet.getLastRowNum(); i++) {
        XSSFRow row = sheet.getRow(i);
        if (row == null) continue;
        // 读取第一列(索引0)的名
        XSSFCell firstNameCell = row.getCell(0);
        if (firstNameCell != null) {
            firstNameList.add(firstNameCell.getStringCellValue().trim());
        }
        // 读取第二列(索引1)的姓
        XSSFCell lastNameCell = row.getCell(1);
        if (lastNameCell != null) {
            lastNameList.add(lastNameCell.getStringCellValue().trim());
        }
    }
}

// 每次需要随机姓名直接调用该方法
public String getRandomFullName() {
    int firstIndex = random.nextInt(firstNameList.size());
    int lastIndex = random.nextInt(lastNameList.size());
    // 可根据需求调整姓名拼接顺序和分隔符
    return firstNameList.get(firstIndex) + " " + lastNameList.get(lastIndex);
}

可选优化点

  • 多线程场景下替换Random为ThreadLocalRandom.current().nextInt(列表长度),避免线程竞争开销
  • 需要生成不重复随机姓名时,可额外维护已使用索引的去重集合,用完清空即可
  • 空行、空单元格已做兼容处理,可根据业务需求调整校验逻辑

内容的提问来源于stack exchange,提问作者GSN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:36:03