Products Technologies Demo Docs Blog Support Company

Text to Table and Table to Text in TX Text Control and C#

TX Text Control provides powerful table features and also full access to text formatting which can be used to create tables from text and vice versa. This article shows how to convert text to tables and tables to text.

Text to Table and Table to Text in TX Text Control and C#

A typical task in document layout is to convert plain text tables created with tab stops into fully formatted tables. In this article we will show you how to convert plain text tables to tables by detecting the tab stops and converting them to table cells including the positions.

Table to Text

Let's start with a simple table in TX Text Control:

Table in TX Text Control

To convert the table, we need to loop through all the rows and columns and create line strings that contain the text of each table cell separated by tab stops. The following code shows how to convert a table to a plain text table with tab stops:

private void ConvertTableToText(TXTextControl.Table table, TXTextControl.TextControl textControl)
{
        if (table.NestedTables.Count >= 1)
        {
                // throw an exception
                throw new Exception("Nested tables are not supported.");
        }

        // Create a new StringBuilder object
        StringBuilder sb = new StringBuilder();

        var numRows = table.Rows.Count;
        var numCols = table.Columns.Count;

        int[] tabStopLocations = new int[14];

        // Loop through all rows
        for (int i = 1; i <= numRows; i++)
        {
                var offset = 0;

                // Loop through all columns
                for (int j = 1; j <= numCols; j++)
                {
                        var position = table.Columns[j].Position;

                        if (j == 1)
                        {
                                if (position > 0)
                                {
                                        tabStopLocations[j - 1] = position;
                                }
                                else
                                {
                                        offset = 1;
                                }
                        }
                        else
                        {
                                tabStopLocations[j - 1 - offset] = position;
                        }

                        if (j > 1 || (j == 1 && position > 0))
                        {
                                sb.Append("\t");
                        }

                        sb.Append(table.Cells[i, j].Text);
                }

                // Append a new line character to the StringBuilder object
                sb.Append("\r\n");
        }

        // Remove table
        table.Select();
        textControl1.Tables.Remove();

        textControl1.Selection.ParagraphFormat.TabPositions = tabStopLocations;

        // Set the text of the TextControl
        textControl1.Selection.Text = sb.ToString();
}

The above code uses StringBuilder to create the plain text table. Each table row is represented by a line string that contains the text of each table cell separated by tab stops. The TableColumn.Position property is used to get the position of the table column in the table. This position is used to determine the tab stop position in the plain text table.

The following animated screenshot shows the result of the conversion:

Table in TX Text Control

In the next screenshot, you can see how different column sizes are handled and converted to a plain text table:

Table in TX Text Control

Text to Table

Now, let's convert the plain text table back to a table in TX Text Control. The following code shows how to convert a plain text table with tab stops to a fully formatted table:

private void ConvertTextToTable(TXTextControl.TextControl textControl)
{
        if (textControl1.Selection.Length == 0)
        {
                throw new Exception("No text selected.");
        }

        int[] storedTabPositions = textControl1.Selection.ParagraphFormat.TabPositions;

        int startPosition = textControl1.Selection.Start;
        int endPosition = startPosition + textControl1.Selection.Length;

        var startLine = textControl1.Lines.GetItem(startPosition);
        var endLine = textControl1.Lines.GetItem(endPosition - 1);

        List<string> lineText = new List<string>();

        // Loop through all lines and add the text of each line to the list
        for (int i = startLine.Number; i <= endLine.Number; i++)
        {
                var line = textControl1.Lines[i];
                lineText.Add(line.Text);
        }

        // Calculate the number of rows and columns
        int numRows = endLine.Number - startLine.Number + 1;
        int numCols = lineText[0].Split('\t').Length;

        textControl1.Selection.Text = string.Empty;

        // Create a new table
        var tableInserted = textControl1.Tables.Add(numRows, numCols);

        // Set input position to the first cell
        textControl1.Selection.Start -= 1;

        // Loop through all rows and columns to populate the table
        for (int i = 1; i <= numRows; i++)
        {
                string[] splitText = lineText[i - 1].Split('\t');

                for (int j = 1; j <= numCols; j++)
                {
                        var tableCell = textControl1.Tables.GetItem().Cells[i, j];

                        // Set the text of the cell, and remove the last CRLF
                        tableCell.Text = (splitText.Length >= j) ? splitText[j - 1].TrimEnd('\r', '\n') : string.Empty;

                        // Set the tab position if it's not the first column and the tab position exists
                        if (j > 1 && storedTabPositions.Length >= j - 1 && storedTabPositions[j - 1] != 0)
                        {
                                tableCell.Position = storedTabPositions[j - 2];
                        }
                }
        }
}

This is basically the reverse operation of the first code snippet. The plain text table is split into lines and each line is split by tab stops. The tab stop positions are used to create table columns and the text is inserted into the table cells.

The plain text table to be converted must be selected first. The following animated screenshot shows the result of the conversion:

Table in TX Text Control

It is important to note that this only works for simple tables with tab stops. More complex tables with merged cells or different column widths require a more sophisticated algorithm to convert the plain text table into a fully formatted table. However, this simple approach is sufficient for most cases.

Conclusion

This article showed how to convert plain text tables with tab stops to fully formatted tables in TX Text Control and how to convert tables to plain text tables. The key to this conversion is the detection of tab stops and the correct positioning of the table cells.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

Related Posts

ASP.NETWindows FormsASP.NET Core

Splitting Tables at Bookmark Positions and Cloning Table Headers

This article shows how to split tables at bookmark positions and how to clone table headers in TX Text Control .NET for Windows Forms and TX Text Control .NET Server.


ASP.NETWindows FormsExcel

Loading and Processing Excel XLSX Spreadsheet Tables into TX Text Control…

TX Text Control provides a powerful API to load and process Excel spreadsheet tables in .NET applications. This article shows how to load an Excel file and process the tables using TX Text Control…


ASP.NETWindows FormsWPF

Inserting MergeBlocks with the DataSourceManager and Applying Table Styles in C#

This article shows how to insert MergeBlocks with the DataSourceManager and how to apply table styles to those tables. The article uses the DocumentServer class to insert MergeBlocks with the…


ASP.NETWindows FormsWPF

Useful Tricks for Working with Tables

When you are working with complex and long tables, it can be useful to know if a table is broken up across multiple pages. These code snippets will help you with various table related tasks.


ASP.NETWindows FormsWPF

Generating Hierarchical Tables from JSON Data in .NET C#

Using TX Text Control, you can generate complex hierarchical tables directly from JSON data. This article explains the code and logic behind it.