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

AnyLogic学生版能否通过代码写入导入的Excel数据库?

在AnyLogic学生版中实现Excel运行时写入操作

AnyLogic学生版确实没有内置的可视化Excel写入工具,但可以通过编写Java代码调用Apache POI库实现运行时修改Excel数据,同步机器状态。以下是具体实现方案:

实现步骤

1. 确认依赖支持

AnyLogic默认已集成Apache POI核心组件,无需额外下载JAR包;若项目出现POI类找不到的情况,可自行下载poi.jar和poi-ooxml.jar,放入项目lib文件夹后,在AnyLogic项目属性 > 库中添加这两个文件作为依赖。

2. 编写状态更新代码

创建一个可复用函数,用于根据机器名称修改对应行的可用性状态:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

// 更新指定机器的可用性状态
public void updateMachineStatus(String targetMachine, boolean newStatus) {
    // 替换为你的Excel文件路径(使用正斜杠/或双反斜杠\\)
    String excelFilePath = "./data/machine_status.xlsx";

    try (FileInputStream inputStream = new FileInputStream(excelFilePath);
         Workbook workbook = new XSSFWorkbook(inputStream)) {

        Sheet dataSheet = workbook.getSheetAt(0); // 假设数据存储在第一个工作表
        Row headerRow = dataSheet.getRow(0); // 假设表头位于第1行(索引0)
        int machineNameCol = -1;
        int statusCol = -1;

        // 定位表头列索引
        for (Cell cell : headerRow) {
            String cellText = cell.getStringCellValue().trim();
            if (cellText.equals("机器名称")) {
                machineNameCol = cell.getColumnIndex();
            } else if (cellText.equals("可用性状态")) {
                statusCol = cell.getColumnIndex();
            }
        }

        if (machineNameCol == -1 || statusCol == -1) {
            throw new RuntimeException("未找到机器名称或可用性状态列");
        }

        // 遍历数据行,找到目标机器并更新状态
        for (int rowIdx = 1; rowIdx <= dataSheet.getLastRowNum(); rowIdx++) {
            Row currentRow = dataSheet.getRow(rowIdx);
            if (currentRow == null) continue;

            Cell machineCell = currentRow.getCell(machineNameCol);
            if (machineCell == null) continue;

            String machineName = machineCell.getStringCellValue().trim();
            if (machineName.equals(targetMachine)) {
                // 更新状态单元格
                Cell statusCell = currentRow.createCell(statusCol);
                statusCell.setCellValue(newStatus);
                break; // 找到目标机器后停止遍历
            }
        }

        // 将修改写入回Excel文件
        try (FileOutputStream outputStream = new FileOutputStream(excelFilePath)) {
            workbook.write(outputStream);
        }

    } catch (IOException e) {
        e.printStackTrace();
        // 可根据需求添加错误处理逻辑,比如弹窗提示写入失败
    }
}

3. 调用更新函数

在机器状态发生改变的逻辑处(比如故障触发、修复完成时),直接调用该函数:

// 示例:将"机器1"的状态设置为不可用
updateMachineStatus("机器1", false);

注意事项

  • 确保Excel文件在模拟运行时未被其他程序(如Excel软件)占用,否则会出现写入权限异常
  • 建议使用项目相对路径指定Excel文件位置,避免绝对路径导致的跨设备运行问题
  • 若使用.xls格式的Excel文件,需将XSSFWorkbook替换为HSSFWorkbook

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:12:52