Created
August 4, 2023 14:35
-
-
Save bjoerntx/4411663a63e0d1813fe3a286ca341a54 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create a hierarchical table from a list of JSON objects | |
private void CreateTable(List<JObject> dataObjects) { | |
// Get the number of columns of the first object | |
int columns = dataObjects[0].Values().Count(); | |
// Check if the first object contains an array and reduce the number of columns | |
columns -= dataObjects[0].Values().Count(value => value.Type == JTokenType.Array); | |
// Add a table with the number of columns | |
Table table = AddTableAtInputPosition(1, columns); | |
int row = 1; | |
// Loop through all objects | |
foreach (JObject dataObject in dataObjects) { | |
// Check if the row is not the first row and add a new row | |
if (row != 1) { | |
table.Cells.GetItem(row - 1, 1).Select(); | |
textControl1.Selection.Start += textControl1.Selection.Length; | |
textControl1.Selection.Length = 0; | |
textControl1.Selection.Start -= 1; | |
// Add a new row after the current row | |
table.Rows.Add(TXTextControl.TableAddPosition.After, 1); | |
// Set the left text distance to 0 to remove the indent | |
table.Rows.GetItem().CellFormat.LeftTextDistance = 0; | |
// Split all cells | |
table.SplitCells(); | |
} | |
int col = 1; | |
// Loop through all properties of the object | |
foreach (var info in dataObject) { | |
// Check if the property is an array | |
if (dataObject[info.Key].Type == JTokenType.Array) { | |
textControl1.Selection.Start = table.Cells.GetItem(row, 1).Start; | |
table.Rows.Add(TXTextControl.TableAddPosition.After, 1); | |
// Set the left text distance to indent the nested table | |
table.Rows.GetItem().CellFormat.LeftTextDistance = 600; | |
// Select the new row and merge all cells | |
table.Select(row + 1, 1, row + 1, table.Columns.Count); | |
table.MergeCells(); | |
// Create a new table for the array | |
List<JObject> subObject = | |
dataObject[info.Key]?.Select(x => x as JObject).ToList(); | |
// recursively call the method to create a new nested table | |
if (subObject != null) { | |
CreateTable(subObject); | |
row++; | |
} | |
} | |
else { // Add the value to the table cell | |
table.Cells.GetItem(row, col).Text = info.Value?.ToString(); | |
col++; | |
} | |
} | |
row++; | |
} | |
} | |
// Add a table at the current input position and return the table object | |
private Table AddTableAtInputPosition(int rows, int columns) { | |
textControl1.Tables.Add(rows, columns); | |
textControl1.Selection.Start -= 1; | |
return textControl1.Tables.GetItem(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment