Create a NetLogic that exports table data to CSV
Export project data to a CSV file.
TIP:
Instead of creating a script from scratch, you can use a predefined one. The predefined script implementation differs from the custom script implementation.
For more information, select from the toolbar and search for
Template Libraries
Generic Table Exporter
Prerequisites
Set the default external code editor. See Set the default code editor.
- InProject view, right-click theNetLogicfolder and select .
- Hover-over the NetLogic, select , and enterExportTableData.
- Double-click the NetLogic.The external code editor opens.
- In the code editor, replace the existing code with the following code: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, ""); } } }
- Save the code.
Provide Feedback