创建用于将表格数据导出到 CSV 的 NetLogic

将项目数据导出到 CSV 文件。
小贴士:
可以使用预定义的脚本,而无需从头开始创建脚本。预定义脚本实现与自定义脚本实现不同。
有关更多信息,请从工具栏中选择
模板库
并搜索
Generic Table Exporter
先决条件
设置默认外部代码编辑器。请参见设置默认代码编辑器
  1. 创建用于将表格数据导出到 CSV 的 NetLogic
  2. 项目视图
    中,右键单击
    NetLogic
    文件夹,然后选择
    新建
    运行时 NetLogic
  3. 将光标悬停在 NetLogic 上,选择
    Edit
    并输入
    ExportTableData
  4. 双击 NetLogic。
    外部代码编辑器将打开。
  5. 在代码编辑器中,使用以下代码替换现有代码:
    using System; using FTOptix.Core; using Store = FTOptix.Store; using HMIProject = FTOptix.HMIProject; using UAManagedCore; using System.IO; public class ExportTableData : FTOptix.NetLogic.BaseNetLogic { [FTOptix.NetLogic.ExportMethod] public void ExportCSV(UAManagedCore.NodeId tableNodeId) { // Getting the current project var project = HMIProject.Project.Current; // Getting the object table from its NodeId var tableObject = LogicObject.Context.GetObject(tableNodeId); if (tableObject == null) return; // Getting the Tables collection var tablesCollection = tableObject.Owner; if (tablesCollection == null) return; // Getting the Store var storeObject = tablesCollection.Owner as Store.Store; object[,] resultSet; string[] header; // Execute query on store of the current project storeObject.Query("SELECT * FROM \"" + tableObject.BrowseName + "\"", out header, out resultSet); // Check if the resultSet is a bidimensional array if (resultSet.Rank != 2) return; // Getting the number of rows and columns of the matrix var rowCount = resultSet != null ? resultSet.GetLength(0) : 0; var columnCount = header != null ? header.Length : 0; // Outpt file path string filePath = Path.Combine(project.ApplicationDirectory, "CSVExport-" + tableObject.BrowseName + "-" + DateTime.UtcNow.ToString("yyyyMMddHHmmss") + ".csv"); Log.Info(filePath); // Writing CSV to file try { using (StreamWriter csvFileStream = new StreamWriter(filePath)) { // Table header for (UInt32 i = 0; i < columnCount; i++) { csvFileStream.Write(header[i]); if (i < columnCount - 1) csvFileStream.Write(";"); } csvFileStream.Write("\n"); // Table content for (UInt32 i = 0; i < rowCount; i++) { for (UInt32 j = 0; j < columnCount; j++) { if (resultSet[i, j] == null) csvFileStream.Write(""); csvFileStream.Write(resultSet[i, j]); if (j < columnCount - 1) csvFileStream.Write(";"); } csvFileStream.Write("\n"); } } } catch(Exception e) { // Write the error in the log UAManagedCore.Logging.LogManager.CoreLogger.Log( UAManagedCore.Logging.LogLevel.Error, "", 0, 0, "Unable to export table '" + tableObject.BrowseName + "' to CSV file '" + filePath + "': " + e.Message, ""); } } }
  6. 保存代码。
提供反馈
对本文档有问题或反馈吗? 请在这里提交您的反馈