我想在某个事件触发时将 AnyLogic 数据库导出到 Excel。
是的,您可以以编程方式从 AnyLogic 数据库中导出表格(即,执行手动“将表格导出到 Excel”或自动“在模型执行结束时导出表格”所做的事情)。但是,是的,没有关于此的真正文档,并且从帮助中的 API 参考中找出所需的逻辑并不容易(尤其是当前在 exportToExternalDB 方法的详细信息中存在错误,尽管 AnyLogic 应该正在修复该文档很快)。
代码示例如下。除了您的要求之外,这样做的主要原因是它允许您动态确定输出文件名(或动态确定输出哪些表)。
NB:这要求 Excel 文件存在,所需的工作表和列名标题行已经存在。但是您可以手动导出一次空表来生成它(并且,如果您想更改输出文件名,您可以在导出之前添加代码,使用标准 Java 文件处理将导出的骨架文件复制到您所需的名称文件代码)。
还有一种方法可以通过编程方式创建 Excel 文件和所需的“骨架”内容,使用更底层的 Java 和 AnyLogic 在幕后使用的 Apache POI library 连接到 Excel。这也可以用来解决你的附属问题(见下文)。
Database outExcel = new Database(this, "ExcelOutput", "outputTest.xlsx");
outExcel.connect();
ModelDatabase modelDB = getEngine().getModelDatabase();
Connection connection = outExcel.getConnection();
// Do the actual per-table export; repeat per table to output
// This requires the Excel file to have the required sheets and header rows
// therein
modelDB.exportToExternalDB("output_sample", // Table name
connection, // External connection
"output_sample", // Target worksheet name
false, // Clear table prior to copy
true); // Auto-commit
outExcel.disconnect();
您能否从 Anylogic 1. 在 Excel 中创建新的工作表来写入数据? 2. 重新标记工作表,以便名称可以包括时间戳?
示例代码如下(您的输出文件名存储在String 变量fileName 中)。请注意,这是使用 Apache POI 的“独立于 AnyLogic”的 Java;此代码中没有任何内容使用任何 AnyLogic 类。因为 AnyLogic 已经在内部包含了 Apache POI 作为库,所以您不需要添加任何东西作为模型依赖项。
try (FileOutputStream fileOut = new FileOutputStream(fileName)) {
Workbook wb = new XSSFWorkbook();
// Create a worksheet for the table
Sheet sheet = wb.createSheet("output_table");
// Create a header row with the required column names in. Row indices are 0 based
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("col1");
row.createCell(1).setCellValue("col2");
row.createCell(2).setCellValue("col3");
// Write the output to a file
wb.write(fileOut);
} catch (Exception e) {
[Handle exceptions in some way]
}
您需要在此代码所在的代理/实验中使用一些必需的 import 语句(在“属性”的“导入部分”中):
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;