Skip to content

Instantly share code, notes, and snippets.

@bjoerntx
Created August 15, 2023 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjoerntx/3f91087290538d347756c6cc3774b8a9 to your computer and use it in GitHub Desktop.
Save bjoerntx/3f91087290538d347756c6cc3774b8a9 to your computer and use it in GitHub Desktop.
// 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