DEV Community

Pilalo Jovanitho
Pilalo Jovanitho

Posted on

How to Set Text Direction in Word

In the world of automated reporting, the visual consistency of a document is just as critical as the data it contains. For developers working with enterprise solutions, generating a Word document programmatically is often only half the battle. The other half lies in ensuring the layout is readable, professional, and strictly adheres to formatting guidelines.

One of the most common pain points in this process is table formatting. When data is pumped into a table dynamically, Word's default auto-sizing behavior often leads to narrow columns for text fields and excessive white space for numeric data. Manually adjusting these widths in a bulk report generation scenario is not feasible. Consequently, learning how to programmatically manage C# Word table column width becomes an essential skill for maintaining document integrity.

This post explores how to take precise control over your document layouts by adjusting table column sizes using Spire.Doc for .NET.

Prerequisites and the Tool of Choice

To manipulate Word documents without relying on Microsoft Office Interop—which requires Word to be installed on the server—developers typically turn to third-party libraries. For this tutorial, we will use Spire.Doc for .NET.

Spire.Doc is a robust library that allows developers to create, read, edit, convert, and print Word documents from any .NET (C#, VB.NET, ASP.NET) platform. It provides a rich object model that maps closely to the standard Word structure, making it intuitive to access tables, rows, and cells.

The specific problem we are addressing is how to adjust table column size reliably, ensuring that when a report is generated, the tables are formatted correctly immediately upon opening.

Preparing the Document

Before we can set widths, we need a document with a table. The following snippet demonstrates how to initialize a document and create a simple table with a few rows and columns.

// Create a new Document instance
Document doc = new Document();

// Add a section
Section section = doc.AddSection();

// Add a table to the section
Table table = section.AddTable(true);

// Define the table dimensions (3 rows, 4 columns)
table.ResetCells(3, 4);

// Add some sample data (optional)
for (int row = 0; row < 3; row++)
{
    for (int col = 0; col < 4; col++)
    {
        table[row, col].AddParagraph().AppendText($"Row {row}, Col {col}");
    }
}
Enter fullscreen mode Exit fullscreen mode

At this stage, the table exists, but its column widths are determined by default behaviors. To enforce a specific design, we must intervene programmatically.

Methods to Adjust Table Column Size

There are two primary ways to handle column widths in Spire.Doc: setting the width for individual cells (which effectively simulates column width) or setting the width for the entire column at once.

Approach 1: Setting Width via Cell Iteration

If you need granular control—perhaps where a specific row requires different sizing than the rest—you can iterate through the rows and set the width for the cell at a specific index. This method is particularly useful for fixed-width layouts.

// Loop through each row in the table
for (int i = 0; i < table.Rows.Count; i++)
{
    // Set the width of the first cell in every row to 100 points
    // This ensures the first column is exactly 100 points wide
    table.Rows[i].Cells[0].SetCellWidth(100, CellWidthType.Point);

    // Set the second column to 200 points
    table.Rows[i].Cells[1].SetCellWidth(200, CellWidthType.Point);
}
Enter fullscreen mode Exit fullscreen mode

In this code, CellWidthType.Point specifies that the unit of measurement is the point (1/72 inch). You could also use CellWidthType.Percentage if you prefer responsive widths relative to the page width.

Approach 2: Using the Table Column Method

While iterating through cells works, Spire.Doc offers a more streamlined API designed specifically for columns. The Table.SetColumnWidth method allows you to define the width for an entire column index in a single call. This is generally the preferred method for standard table formatting.

// Set the width of the 1st column (index 0) to 150 points
table.SetColumnWidth(0, 150, CellWidthType.Point);

// Set the width of the 2nd column (index 1) to 250 points
table.SetColumnWidth(1, 250, CellWidthType.Point);

// Set the remaining columns to AutoFit to contents
table.ResetCells(3, 4); // Note: ResetCells may clear widths, so set widths after.
// Alternatively, use AutoFit behavior for the rest
table.AutoFit(AutoFitBehaviorType.AutoFitToContents);
Enter fullscreen mode Exit fullscreen mode

This approach is cleaner and easier to maintain. By combining fixed widths for key columns (like ID or Date) and AutoFitToContents for descriptive text columns, you can create highly readable reports.

Saving the Result

Once the widths are configured, saving the document is straightforward. It is always good practice to wrap file operations in a using block or try-catch statements to handle IO exceptions.

// Save the document to a file
string outputPath = "FormattedTable.docx";
doc.SaveToFile(outputPath, FileFormat.Docx2013);

// Optional: Open the generated file automatically for review
System.Diagnostics.Process.Start(outputPath);
Enter fullscreen mode Exit fullscreen mode

Conclusion

Achieving precise document layout control is often the differentiator between a basic data dump and a professional report. By leveraging Spire.Doc for .NET, developers can efficiently adjust table column size and eliminate the need for manual post-processing.

Whether you choose to iterate through cells for specific row formatting or utilize the direct SetColumnWidth method for uniformity, the ability to lock down C# Word table column width ensures your documents look exactly as intended, every time they are generated. Integrating these snippets into your automation workflow will result in cleaner, more consistent outputs and save significant time in the long run.

Top comments (0)