Created
August 15, 2023 19:13
-
-
Save bjoerntx/3f91087290538d347756c6cc3774b8a9 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
// convert a flat (non-nested) table to a JSON string | |
private string Table2Data(Table table, bool containsTableHeader) { | |
// create a list of dictionaries | |
var tableList = new List<Dictionary<string, string>>(); | |
// get the start row | |
int startRow = containsTableHeader ? 2 : 1; | |
// iterate through all rows | |
for (int row = startRow; row < table.Rows.Count; row++) { | |
// create a dictionary for each row | |
var rowData = new Dictionary<string, string>(); | |
// iterate through all columns | |
for (int col = 1; col < table.Columns.Count; col++) { | |
// get the column title from the first row | |
var columnTitle = containsTableHeader ? | |
table.Cells[1, col].Text.Trim('\t') : $"Column {col}"; | |
// add the cell text to the dictionary | |
rowData[columnTitle] = table.Cells[row, col].Text.Trim('\t'); | |
} | |
// add the dictionary to the list | |
tableList.Add(rowData); | |
} | |
// return the JSON string | |
return System.Text.Json.JsonSerializer.Serialize(tableList, new JsonSerializerOptions { WriteIndented = true }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment