With TX Text Control, the most flexible and complete library, you can programmatically generate MS Word DOCX files in .NET applications running on Windows and Linux. You can either create these documents from scratch or generate them from existing templates by merging data into placeholders or by assembling documents from different sources and other document types.
This tutorial will guide you through the steps necessary to create a new DOCX file from scratch and show you how to add specific elements to it programmatically.
Prerequisites
You need to download and install the trial version of TX Text Control .NET Server for ASP.NET:
- Download Trial Version
Setup download and installation required.
Creating the Application
Make sure that you downloaded the latest version of Visual Studio 2022 that comes with the .NET 8 SDK.
-
In Visual Studio 2022, create a new project by choosing Create a new project.
-
Select Console App as the project template and confirm with Next.
-
Enter a project name and choose a location to save the project. Confirm with Next.
-
Choose .NET 8.0 (Long Term Support) as the Framework.
-
Enable the Enable container support checkbox and choose Linux as the Container OS.
-
Choose Dockerfile for the Container build type option and confirm with Create.
Adding the NuGet Packages
-
In the Solution Explorer, select your created project and choose Manage NuGet Packages... from the Project main menu. Select Text Control Offline Packages as the Package source.
Install the following package:
- TXTextControl.TextControl.Core.SDK
Creating a Document
-
Find the Program.cs file in the Solution Explorer and replace the code with the following code snippet:
This file contains hidden or 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 charactersusing TXTextControl; using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl()) { tx.Create(); // Add a paragraph to the document TXTextControl.Selection selection = new TXTextControl.Selection(0, 0); selection.Text = "Hello, Office Open XML!"; // Set the paragraph format selection.ParagraphFormat = new ParagraphFormat() { Alignment = HorizontalAlignment.Center, }; // Set the font format selection.FontSize = 240; // 240 twips = 12 pt selection.FontName = "Lato"; selection.Bold = true; // Apply the changes to the document tx.Selection = selection; // Save the document tx.Save("results.docx", TXTextControl.StreamType.WordprocessingML); } -
Now run the project that runs the application in a Docker container, WSL, or locally on your Windows.
It will create a new document that will insert a centered paragraph with bold formatting.
Creating Tables with Formulas (Programmatically)
TX Text Control provides a powerful API for creating tables with formulas. The following code snippet shows how to create a table with formulas to calculate a row total and a total for all rows:
using TXTextControl; | |
class LineItem | |
{ | |
public string Name { get; set; } | |
public string Description { get; set; } | |
public int Quantity { get; set; } | |
public decimal Price { get; set; } | |
} | |
class DocumentGenerator | |
{ | |
const int RowCount = 4; | |
const int ColumnCount = 5; | |
public void CreateDocument() | |
{ | |
using (ServerTextControl tx = new ServerTextControl()) | |
{ | |
tx.Create(); | |
// Add table | |
tx.Tables.Add(RowCount, ColumnCount); | |
Table table = tx.Tables[1]; | |
// Define formats | |
var currencyFormat = new TableCellFormat | |
{ | |
TextType = TextType.Number, | |
NumberFormat = "$#,##0.00" | |
}; | |
// Set column formats | |
table.Columns[4].CellFormat = currencyFormat; | |
table.Columns[5].CellFormat = currencyFormat; | |
// Add line item | |
var lineItem = new LineItem | |
{ | |
Name = "Sample Item", | |
Description = "This is a sample item description.", | |
Quantity = 10, | |
Price = 19.99m | |
}; | |
// Fill rows with data and formulas | |
for (int row = 1; row < RowCount; row++) | |
{ | |
table.Cells[row, 1].Text = lineItem.Name; | |
table.Cells[row, 2].Text = lineItem.Description; | |
table.Cells[row, 3].Text = lineItem.Quantity.ToString(); | |
table.Cells[row, 4].Text = lineItem.Price.ToString(); | |
table.Cells[row, 5].Formula = $"SUM(C{row}*D{row})"; | |
} | |
// Set total formula in last row, last column | |
table.Cells[RowCount, ColumnCount].Formula = "SUM(above)"; | |
// Save document | |
tx.Save("results.docx", StreamType.WordprocessingML); | |
} | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
DocumentGenerator generator = new DocumentGenerator(); | |
generator.CreateDocument(); | |
Console.WriteLine("Document created successfully."); | |
} | |
} |
In this example, we will create a table with 5 columns and 4 rows. The first two columns contain text, and the third column contains the number of items. The fourth column contains the price per item, and the fifth column contains the total price for each row. The last row contains a formula that calculates the total price for all rows.
When you run the application, it creates a new document with a table containing the calculated values:
Creating the Table using MailMerge
One way to create these tables with formulas is to create them programmatically using the very powerful and flexible API as shown above. But another way is to prepare a template with the ready-made table and formulas and merge JSON data into it.
This allows the user to design the table exactly as needed. The advantage of TX Text Control is that it comes with a programmable document editor (the only true WYSIWYG editor on the market) that can be given to end users to design their templates.
This is what the same table looks like in TX Text Control. It has a more polished design, with merge fields and formulas added.
The following JSON data is used to merge the table with the line item data:
[ | |
{ | |
"line-items": [ | |
{ | |
"Name": "Wireless Mouse", | |
"Description": "Ergonomic wireless mouse with USB receiver", | |
"Quantity": 2, | |
"Price": 25.99 | |
}, | |
{ | |
"Name": "Mechanical Keyboard", | |
"Description": "Backlit mechanical keyboard with blue switches", | |
"Quantity": 1, | |
"Price": 79.50 | |
}, | |
{ | |
"Name": "HDMI Cable", | |
"Description": "2-meter high-speed HDMI cable", | |
"Quantity": 3, | |
"Price": 8.75 | |
} | |
] | |
} | |
] |
And the following code snippet shows how to merge the JSON data into the template:
using TXTextControl; | |
using TXTextControl.DocumentServer; | |
const string TemplatePath = "template.tx"; | |
const string JsonDataPath = "data.json"; | |
const string OutputPath = "results.docx"; | |
string jsonData = File.ReadAllText(JsonDataPath); | |
using (var tx = new ServerTextControl()) | |
{ | |
tx.Create(); | |
// Load the template document | |
tx.Load(TemplatePath, StreamType.InternalUnicodeFormat); | |
// Perform the merge | |
var mailMerge = new MailMerge { TextComponent = tx }; | |
mailMerge.MergeJsonData(jsonData); | |
// Save the merged document | |
tx.Save(OutputPath, StreamType.WordprocessingML); | |
} |
When you run the application, it creates a new document with a table containing the calculated values:
Conclusion
TX Text Control provides a powerful API for creating documents programmatically. It allows you to create tables with formulas and merge JSON data into templates. This makes it easy to create complex documents with dynamic content.
In this tutorial, we have shown you how to create a new DOCX file from scratch and how to add specific elements to it programmatically. We also showed you how to create tables with formulas and merge JSON data into templates.