C#: Merge or Split Tables in Word
Tables in Word documents allow users to organize data in a clear and structured manner. However, as documents grow in complexity, the need to adjust table structures often arises. Whether you need to combine multiple tables for a comprehensive view or divide a large table for better readability, mastering the art of merging and splitting tables in Word can significantly improve the presentation of your data. In this article, you will learn how to merge or split tables in Word in C# using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Merge Tables in Word in C#
With Spire.Doc for .NET, you can combine two or more tables into one by copying all rows from other tables to the target table and then deleting the other tables. The following are the detailed steps.
- Create a Document instance.
- Load a Word document using Document.LoadFromFile() method.
- Get a specified section using Document.Sections[] property.
- Get two tables in the section using section.Tables[] property.
- Iterate through all rows in the second table and copy them using Table.Rows[].Clone() method.
- Add the rows of the second table to the first table using Table.Rows.Add() method.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc; namespace CombineTables { class Program { static void Main(string[] args) { //Create a Document instance Document doc = new Document(); //Load a Word document doc.LoadFromFile("Cost.docx"); //Get the first section Section section = doc.Sections[0]; //Get the first and second table in the section Table table1 = section.Tables[0] as Table; Table table2 = section.Tables[1] as Table; //Add the rows of table2 to table1 for (int i = 0; i < table2.Rows.Count; i++) { table1.Rows.Add(table2.Rows[i].Clone()); } //Remove the table2 section.Tables.Remove(table2); //Save the result document doc.SaveToFile("CombineTables.docx", FileFormat.Docx); } } }
Split Tables in Word in C#
To split a table into two or more tables, you need to create a new table, then copy the specified rows from the original table to the new table, and then delete those rows from the original table. The following are the detailed steps.
- Create a Document instance.
- Load a Word document using Document.LoadFromFile() method.
- Get a specified section using Document.Sections[] property.
- Get a specified table in the section using section.Tables[] property.
- Specify the row index where the table will be split.
- Create a new instance of the Table class.
- Iterate through the specified rows in the original table and copy them using Table.Rows[].Clone() method.
- Add the specified rows to the new table using Table.Rows.Add() method.
- Iterate through the copied rows and remove each row from the original table using Table.Rows.RemoveAt() method.
- Add the new table to the section using Section.Tables.Add() method.
- Save the result document using Document.SaveToFile() method.
- C#
using Spire.Doc; namespace SplitWordTable { class Program { static void Main(string[] args) { //Create a Document instance Document doc = new Document(); //Load a Word document doc.LoadFromFile("CombineTables.docx"); //Get the first section Section section = doc.Sections[0]; //Get the first table in the section Table table = section.Tables[0] as Table; //Specify to split the table from the fifth row int splitIndex = 4; //Create a new table Table newTable = new Table(section.Document); //Adds rows (from the 5th to the last row) to the new table for (int i = splitIndex; i < table.Rows.Count; i++) { newTable.Rows.Add(table.Rows[i].Clone()); } //Delete rows from the original table for (int i = table.Rows.Count - 1; i >= splitIndex; i--) { table.Rows.RemoveAt(i); } //Add the new table to the section section.Tables.Add(newTable); //Save the result document doc.SaveToFile("SplitTable.docx", FileFormat.Docx); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#: Set the Column Width of a Word Table
Setting the column width in Word tables is crucial for optimizing document readability and aesthetics. Appropriate column widths prevent long lines of text from hindering readability, particularly in text-dense tables. Word offers two approaches: percentages and fixed values. Setting column widths using percentage values allows tables to adapt to different screen sizes, keeping content neatly aligned and enhancing the reading experience. Using fixed values, on the other hand, precisely controls the structure of the table, ensuring consistency and professionalism, making it suitable for designs with strict data alignment requirements or complex layouts. This article will introduce how to set Word table column width based on percentage or fixed value settings using Spire.Doc for .NET in C# projects.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Set Column Width Based on Percentage in C#
When setting column widths in a Word table using percentage values, you first need to set the table's preferred width type to percentage. This is done with Table.PreferredWidth = new PreferredWidth(WidthType.Percentage, (short)100). Then, iterate through each column and set the width to the same or different percentage values as required. Here are the detailed steps:
- Create a Document object.
- Load a document using the Document.LoadFromFile() method.
- Retrieve the first section of the document using Document.Sections[0].
- Get the first table within the section using Section.Tables[0].
- Use a for loop to iterate through all rows in the table.
- Set the column width for cells in different columns to percentage values using the TableRow.Cells[index].SetCellWidth(value, CellWidthType.Percentage) method.
- Save the changes to the Word document using the Document.SaveToFile() method.
- C#
using Spire.Doc; namespace SpireDocDemo { internal class Program { static void Main(string[] args) { // Create a new Document object Document doc = new Document(); // Load the document named "example.docx" doc.LoadFromFile("Sample.docx"); // Get the first Section of the document Section section = doc.Sections[0]; // Cast the first Table in the Section to Table type Table table = (Table)section.Tables[0]; // Create a PreferredWidth object, set the width type to Percentage, and set the width value to 100% PreferredWidth percentageWidth = new PreferredWidth(WidthType.Percentage, (short)100); // Set the preferred width of the Table to the PreferredWidth object created above table.PreferredWidth = percentageWidth; // Define a variable of type TableRow TableRow tableRow; // Iterate through all rows in the Table for (int i = 0; i < table.Rows.Count; i++) { // Get the current row tableRow = table.Rows[i]; // Set the width of the first column cell to 34%, with the type as Percentage tableRow.Cells[0].SetCellWidth(34, CellWidthType.Percentage); // Set the width of the second column cell to 33%, with the type as Percentage tableRow.Cells[1].SetCellWidth(33, CellWidthType.Percentage); // Set the width of the third column cell to 33%, with the type as Percentage tableRow.Cells[2].SetCellWidth(33, CellWidthType.Percentage); } // Save the modified document, specifying the file format as Docx2016 doc.SaveToFile("set_column_width_by_percentage.docx", FileFormat.Docx2016); // Close the document doc.Close(); } } }
Set Column Width Based on Fixed Value in C#
When setting column widths in a Word table using fixed values, you first need to set the table's layout to fixed. This is done with Table.TableFormat.LayoutType = LayoutType.Fixed. Then, iterate through each column and set the width to the same or different fixed values as required. Here are the detailed steps:
- Create a Document object.
- Load a document using the Document.LoadFromFile() method.
- Retrieve the first section of the document using Document.Sections[0].
- Get the first table within the section using Section.Tables[0].
- Use a for loop to iterate through all rows in the table.
- Set the column width for cells in different columns to fixed values using the TableRow.Cells[index].SetCellWidth(value, CellWidthType.Point) method. Note that value should be replaced with the desired width in points.
- Save the changes to the Word document using the Document.SaveToFile() method.
- C#
using Spire.Doc; namespace SpireDocDemo { internal class Program { static void Main(string[] args) { // Create a new Document object Document doc = new Document(); // Load the document doc.LoadFromFile("Sample.docx"); // Get the first Section of the document Section section = doc.Sections[0]; // Cast the first Table in the Section to Table type Table table = (Table)section.Tables[0]; // Set the table layout type to Fixed table.TableFormat.LayoutType = LayoutType.Fixed; // Set the table resizing mode to not auto-resize table.TableFormat.IsAutoResized = false; // Get the left margin float leftMargin = section.PageSetup.Margins.Left; // Get the right margin float rightMargin = section.PageSetup.Margins.Right; // Calculate the page width minus the left and right margins double pageWidth = section.PageSetup.PageSize.Width - leftMargin - rightMargin; // Define a variable of type TableRow TableRow tableRow; // Loop through all rows in the Table for (int i = 0; i < table.Rows.Count; i++) { // Get the current row tableRow = table.Rows[i]; // Set the width of the first column cell to 34% of the page width tableRow.Cells[0].SetCellWidth((float)(pageWidth * 0.34), CellWidthType.Point); // Set the width of the second column cell to 33% of the page width tableRow.Cells[1].SetCellWidth((float)(pageWidth * 0.33), CellWidthType.Point); // Set the width of the third column cell to 33% of the page width tableRow.Cells[2].SetCellWidth((float)(pageWidth * 0.33), CellWidthType.Point); } // Save the modified document, specifying the file format as Docx2016 doc.SaveToFile("set_column_width_to_fixed_value.docx", FileFormat.Docx2016); // Close the document doc.Close(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#: Extract Tables from Word Documents
Tables in Word documents often contain valuable information, ranging from financial data and research results to survey results and statistical records. Extracting the data contained within these tables can unlock a wealth of opportunities, empowering you to leverage it for a variety of purposes, such as in-depth data analysis, trend identification, and seamless integration with other tools or databases. In this article, we will demonstrate how to extract tables from Word documents in C# using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Extract Tables from Word in C#
In Spire.Doc for .NET, the Section.Tables property is used to access the tables contained within a section of a Word document. This property returns a collection of ITable objects, where each object represents a distinct table in the section. Once you have the ITable objects, you can iterate through their rows and cells, and then retrieve the textual content of each cell using cell.Paragraphs[index].Text property.
The detailed steps to extract tables from a Word document are as follows:
- Create an object of the Document class and load a Word document using Document.LoadFromFile() method.
- Iterate through the sections in the document and get the table collection of each section through Section.Tables property.
- Iterate through the tables in each section and create a string object for each table.
- Iterate through the rows in each table and the cells in each row, then get the text of each cell through TableCell.Paragraphs[index].Text property and add the cell text to the string.
- Save each string to a text file.
- C#
using Spire.Doc; using Spire.Doc.Collections; using Spire.Doc.Interface; using System.IO; using System.Text; namespace ExtractWordTable { internal class Program { static void Main(string[] args) { // Create an object of the Document class Document doc = new Document(); // Load a Word document doc.LoadFromFile("Tables.docx"); // Iterate through the sections in the document for (int sectionIndex = 0; sectionIndex < doc.Sections.Count; sectionIndex++) { // Get the current section Section section = doc.Sections[sectionIndex]; // Get the table collection of the section TableCollection tables = section.Tables; // Iterate through the tables in the section for (int tableIndex = 0; tableIndex < tables.Count; tableIndex++) { // Get the current table ITable table = tables[tableIndex]; // Initialize a string to store the table data string tableData = ""; // Iterate through the rows in the table for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++) { // Get the current row TableRow row = table.Rows[rowIndex]; // Iterate through the cells in the row for (int cellIndex = 0; cellIndex < row.Cells.Count; cellIndex++) { // Get the current cell TableCell cell = table.Rows[rowIndex].Cells[cellIndex]; // Get the text in the cell string cellText = ""; for (int paraIndex = 0; paraIndex < cell.Paragraphs.Count; paraIndex++) { cellText += (cell.Paragraphs[paraIndex].Text.Trim() + " "); } // Add the text to the string tableData += cellText.Trim(); if (cellIndex < table.Rows[rowIndex].Cells.Count - 1) { tableData += "\t"; } } // Add a new line tableData += "\n"; } // Save the table data to a text file string filePath = Path.Combine("Tables", $"Section{sectionIndex + 1}_Table{tableIndex + 1}.txt"); File.WriteAllText(filePath, tableData, Encoding.UTF8); } } doc.Close(); } } }
Extract Tables from Word to Excel in C#
In addition to saving the extracted table data to text files, you can also write the data directly into Excel worksheets by using the Spire.XLS for .NET library. However, before you can use Spire.XLS, you need to install it via NuGet:
Install-Package Spire.XLS
The detailed steps to extract tables from Word documents to Excel worksheets are as follows:
- Create an object of the Document class and load a Word document using the Document.LoadFromFile() method.
- Create an object of the Workbook class and clear the default worksheets using Workbook.Worksheets.Clear() method.
- Iterate through the sections in the document and get the table collection of each section through Section.Tables property.
- Iterate through the tables in the section and add a worksheet for each table to the workbook using Workbook.Worksheets.Add() method.
- Iterate through the rows in each table and the cells in each row, then get the text of each cell through TableCell.Paragraphs[index].Text property and write the text to the worksheet using Worksheet.SetCellValue() method.
- Save the workbook to an Excel file using Workbook.SaveToFile() method.
- C#
using Spire.Doc; using Spire.Doc.Interface; using Spire.Xls; namespace ExtractWordTableToExcel { internal class Program { static void Main(string[] args) { // Create an object of the Document class Document doc = new Document(); // Load a Word document doc.LoadFromFile("Tables.docx"); // Create an object of the Workbook class Workbook wb = new Workbook(); // Remove the default worksheets wb.Worksheets.Clear(); // Iterate through the sections in the document for (int sectionIndex = 0; sectionIndex < doc.Sections.Count; sectionIndex++) { // Get the current section Section section = doc.Sections[sectionIndex]; // Iterate through the tables in the section for (int tableIndex = 0; tableIndex < section.Tables.Count; tableIndex++) { // Get the current table ITable table = section.Tables[tableIndex]; // Add a worksheet to the workbook Worksheet ws = wb.Worksheets.Add($"Section{sectionIndex + 1}_Table{tableIndex + 1}"); // Iterate through the rows in the table for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++) { // Get the current row TableRow row = table.Rows[rowIndex]; // Iterate through the cells in the row for (int cellIndex = 0; cellIndex < row.Cells.Count; cellIndex++) { // Get the current cell TableCell cell = row.Cells[cellIndex]; // Get the text in the cell string cellText = ""; for (int paraIndex = 0; paraIndex < cell.Paragraphs.Count; paraIndex++) { cellText += (cell.Paragraphs[paraIndex].Text.Trim() + " "); } // Write the cell text to the worksheet ws.SetCellValue(rowIndex + 1, cellIndex + 1, cellText); } // Autofit the width of the columns in the worksheet ws.Range.AutoFitColumns(); } } } // Save the workbook to an Excel file wb.SaveToFile("Tables/WordTableToExcel.xlsx", ExcelVersion.Version2016); doc.Close(); wb.Dispose(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#: Add, Modify, or Remove Word Table Borders
Adding, modifying, and removing Word table borders can enhance the readability, aesthetics, and organization of data. Adding borders makes the content of the table clearer, distinguishing between different cells, which helps readers quickly identify information. Modifying border styles (such as line thickness, color, or pattern) can emphasize key data, guide visual flow, or conform to specific document styles and design requirements. Removing borders, in some cases, reduces visual clutter, making the content more compact and minimalist, especially suitable for data presentation where strict divisions are not needed or when you wish to downplay structural visibility. This article will introduce how to add, modify, or remove Word table borders in C# projects using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
C# Add Word Table Borders
To set borders for all cells in an entire Word table, you need to iterate over each cell and set its visual border properties. Here are the detailed steps:
- Create a Document object.
- Use the Document.LoadFromFile() method to load a document.
- Retrieve the first section of the document using Document.Sections[0].
- Get the first table in that section by using Section.Tables[0].
- Use a for loop to iterate through all the cells in the table.
- Set TableCell.CellFormat.Borders.BorderType to BorderStyle.Single, which sets the cell border to a single line style.
- Set TableCell.CellFormat.Borders.LineWidth to 1.5, defining the border width to be 1.5 points.
- Set TableCell.CellFormat.Borders.Color to Color.Black, setting the border color to black.
- Save the changes to the Word document using the Document.SaveToFile() method.
- C#
using Spire.Doc; namespace SpireDocDemo { internal class Program { static void Main(string[] args) { // Create a new Document object Document doc = new Document(); // Load the document from a file doc.LoadFromFile("TableExample1.docx"); // Get the first section of the document Section section = doc.Sections[0]; // Get the first table in that section Table table = (Table)section.Tables[0]; // Declare TableRow and TableCell variables for use within loops TableRow tableRow; TableCell tableCell; // Iterate through all rows in the table for (int i = 0; i < table.Rows.Count; i++) { // Get the current row tableRow = table.Rows[i]; // Iterate through all cells in the current row for (int j = 0; j < tableRow.Cells.Count; j++) { // Get the current cell tableCell = tableRow.Cells[j]; // Set the border style of the current cell to single line tableCell.CellFormat.Borders.BorderType = Spire.Doc.Documents.BorderStyle.Single; } } // Save the modified document as a new file doc.SaveToFile("AddBorders.docx", FileFormat.Docx2016); // Close the document to release resources doc.Close(); } } }
C# Modify Word Table Borders
Spire.Doc offers a range of border properties such as the border style TableCell.CellFormat.Borders.BorderType, border width TableCell.CellFormat.Borders.LineWidth, and border color TableCell.CellFormat.Borders.Color, among others. You can customize these properties to achieve the desired effects. Below are the detailed steps:
- Create a Document object.
- Load a document using the Document.LoadFromFile() method.
- Retrieve the first section of the document using Document.Sections[0].
- Get the first table in the section using Section.Tables[0].
- Use a for loop to iterate over the cells in the table whose border styles you wish to change.
- Change the bottom border color of the cell by setting TableCell.CellFormat.Borders.Bottom.Color to Color.PaleVioletRed.
- Change the bottom border style of the cell by setting TableCell.CellFormat.Borders.Bottom.BorderType to BorderStyle.DotDash.
- Change the bottom border width of the cell by setting TableCell.CellFormat.Borders.Bottom.LineWidth to 2 points.
- Save the changes to the document using the Document.SaveToFile() method.
- C#
using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; namespace SpireDocDemo { internal class Program { static void Main(string[] args) { // Create a new Document object Document doc = new Document(); // Load the document from a file doc.LoadFromFile("TableExample2.docx"); // Get the first section of the document Section section = doc.Sections[0]; // Get the first table in that section Table table = (Table)section.Tables[0]; // Declare a TableRow to use within the loop TableRow tableRow; // Iterate through all rows of the table for (int i = 1; i < table.Rows.Count - 1; i++) { tableRow = table.Rows[i]; // Set the border color of the current cell tableRow.Cells[1].CellFormat.Borders.Bottom.Color = Color.PaleVioletRed; // Set the border style of the current cell to DotDash tableRow.Cells[1].CellFormat.Borders.Bottom.BorderType = Spire.Doc.Documents.BorderStyle.DotDash; // Set the width of the border tableRow.Cells[1].CellFormat.Borders.Bottom.LineWidth = 2; } // Save the modified document as a new file doc.SaveToFile("ModifiedBorders.docx", FileFormat.Docx2016); // Close the document and release resources doc.Close(); } } }
C# Remove Word Table Borders
During the process of handling Word documents, not only can border styles be applied to entire tables, but customization can also be extended to individual cells. To completely remove all borders from a table, it is recommended to follow a two-step strategy: First, apply border removal settings to the table itself; second, visit each cell within the table individually to clear their border styles. Here are the detailed steps:
- Create a Document object.
- Load a document using the Document.LoadFromFile() method.
- Retrieve the first table in the section using Section.Tables[0].
- Use a for loop to iterate over all cells in the table.
- Set Table.TableFormat.Borders.BorderType = BorderStyle.None to remove borders from the table.
- Set TableCell.CellFormat.Borders.BorderType = BorderStyle.None to remove borders from each cell.
- Save the changes to the Word document using the Document.SaveToFile() method.
- C#
using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; namespace SpireDocDemo { internal class Program { static void Main(string[] args) { // Create a new Document object Document doc = new Document(); // Load the document from file doc.LoadFromFile("TableExample2.docx"); // Get the first section of the document Section section = doc.Sections[0]; // Get the first table in that section Table table = (Table)section.Tables[0]; // Remove the borders set on the table table.TableFormat.Borders.BorderType = BorderStyle.None; // Declare a TableRow to use in the loop TableRow tableRow; // Iterate through all rows in the table for (int i = 0; i < table.Rows.Count; i++) { tableRow = table.Rows[i]; for (int j = 0; j < tableRow.Cells.Count; j++) { // Remove all borders set on the cell tableRow.Cells[j].CellFormat.Borders.BorderType = BorderStyle.None; } } // Save the modified document as a new file doc.SaveToFile("RemoveBorders.docx", FileFormat.Docx2016); // Close the document to release resources doc.Close(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Add/Get Alternative Text of Table in Word in C#
Alternative text (alt text) can help people with screen readers understand the content of our table. This article is going to demonstrate how to add or get the alternative text of a table in a word document using Spire.Doc.
In Spire.Doc, we can set or get the alternative text of a table using the Table.Title and Table.TableDescription properties. The following example shows how to add alternative text to a table.
Detail steps:
Step 1: Instantiate a Document object and load a word document.
Document doc = new Document(); doc.LoadFromFile("Input.docx");
Step 2: Get the first section.
Section section = doc.Sections[0];
Step 3: Get the first table in the section.
Table table = section.Tables[0] as Table;
Step 4: Add alt text to the table.
//Add title table.Title = "Table 1"; //Add description table.TableDescription = "Description Text";
Step 5: Save the document.
doc.SaveToFile("output.docx", FileFormat.Docx2013);
Screenshot:
Full code:
using Spire.Doc; namespace Add_Alt_Text_To_Word_Table { class Program { static void Main(string[] args) { //Instantiate a Document object Document doc = new Document(); //Load a word document doc.LoadFromFile("Input.docx"); //Get the first section Section section = doc.Sections[0]; //Get the first table in the section Table table = section.Tables[0] as Table; //Add alt text //Add tile table.Title = "Table 1"; //Add description table.TableDescription = "Description Text"; //Save the document doc.SaveToFile("output.docx", FileFormat.Docx2013); } } }
How to Create a Nested Table in Word in C#
A nested table is one table placed inside of another, where the larger table functions as a container for the smaller one. Nested tables allow you to arrange different sets of data in groups to show clients.
This article presents how we can create a nested table using Spire.Doc in C#.
Step 1: Create a new PDF document and add a section to it.
Document doc = new Document(); Section section = doc.AddSection();
Step 2: Add a table to the section.
Table table = section.AddTable(true); table.ResetCells(2, 3);
Step 3: Adjust the column with.
table.Rows[0].Cells[0].Width = table.Rows[0].Cells[2].Width = 50F; table.Rows[1].Cells[0].Width = table.Rows[1].Cells[2].Width = 50F; table.AutoFitBehavior(AutoFitBehaviorType.wdAutoFitWindow);
Step 4: Insert content to the cells of the table.
table[0, 0].AddParagraph().AppendText("SI.No."); string text = "Earthwork excavation for foundation of buildings, water supply, " + "sanitary lines and electrical conduits either in pits or in " + "trenches 1.5m and above in width, in ordinary soil not exceeding " + "1.5m in depth including dressing the bottom and sides of pits and " + "trenches, stacking the excavated soil clear."; table[0, 1].AddParagraph().AppendText(text); table[0, 2].AddParagraph().AppendText("Qty");
Step 5: Insert a nested table to the cell (first row, second column).
Table nestedTable= table[0, 1].AddTable(true); nestedTable.ResetCells(3, 4); nestedTable.AutoFitBehavior(AutoFitBehaviorType.wdAutoFitContents);
Step 6: Add content to nested cells.
nestedTable[0, 0].AddParagraph().AppendText("SI.No."); nestedTable[0, 1].AddParagraph().AppendText("Item"); nestedTable[0, 2].AddParagraph().AppendText("Qty"); nestedTable[0, 3].AddParagraph().AppendText("Rate"); nestedTable[1, 0].AddParagraph().AppendText("1"); nestedTable[1, 1].AddParagraph().AppendText("Sand"); nestedTable[1, 2].AddParagraph().AppendText("30"); nestedTable[1, 3].AddParagraph().AppendText("45"); nestedTable[2, 0].AddParagraph().AppendText("2"); nestedTable[2, 1].AddParagraph().AppendText("Cement"); nestedTable[2, 2].AddParagraph().AppendText("30"); nestedTable[2, 3].AddParagraph().AppendText("50");
Step 7: Save the file.
doc.SaveToFile("Nested_Table.docx", FileFormat.Docx2013);
Output:
Full Code:
//create a new pdf document Document doc = new Document(); Section section = doc.AddSection(); //add a table Table table = section.AddTable(true); table.ResetCells(2, 3); //set column width table.Rows[0].Cells[0].Width = table.Rows[0].Cells[2].Width = 50F; table.Rows[1].Cells[0].Width = table.Rows[1].Cells[2].Width = 50F; table.AutoFitBehavior(AutoFitBehaviorType.wdAutoFitWindow); //insert content to cells table[0, 0].AddParagraph().AppendText("SI.No."); string text = "Earthwork excavation for foundation of buildings, water supply, " + "sanitary lines and electrical conduits either in pits or in " + "trenches 1.5m and above in width, in ordinary soil not exceeding " + "1.5m in depth including dressing the bottom and sides of pits and " + "trenches, stacking the excavated soil clear."; table[0, 1].AddParagraph().AppendText(text); table[0, 2].AddParagraph().AppendText("Qty"); //add a nested table to cell(first row, second column) Table nestedTable= table[0, 1].AddTable(true); nestedTable.ResetCells(3, 4); nestedTable.AutoFitBehavior(AutoFitBehaviorType.wdAutoFitContents); //add content to nested cells nestedTable[0, 0].AddParagraph().AppendText("SI.No."); nestedTable[0, 1].AddParagraph().AppendText("Item"); nestedTable[0, 2].AddParagraph().AppendText("Qty"); nestedTable[0, 3].AddParagraph().AppendText("Rate"); nestedTable[1, 0].AddParagraph().AppendText("1"); nestedTable[1, 1].AddParagraph().AppendText("Sand"); nestedTable[1, 2].AddParagraph().AppendText("30"); nestedTable[1, 3].AddParagraph().AppendText("45"); nestedTable[2, 0].AddParagraph().AppendText("2"); nestedTable[2, 1].AddParagraph().AppendText("Cement"); nestedTable[2, 2].AddParagraph().AppendText("30"); nestedTable[2, 3].AddParagraph().AppendText("50"); //save doc.SaveToFile("Nested_Table.docx", FileFormat.Docx2013);
How to Delete Rows and Columns from a Word Table in C#, VB.NET
Adding rows and columns are common tasks in Word table processing, on the contrary, sometimes we also have the requirement of deleting rows or columns from a table. This article demonstrates how to delete a row and a column from an existing Word table using Spire.Doc.
Below is the screenshot of the original table. Afterwards, we will remove the colored row and column from the table.
Detail steps:
Step 1: Instantiate a Document object and load the Word document.
Document doc = new Document(); doc.LoadFromFile("Sample.docx");
Step 2: Get the table from the document.
Table table = doc.Sections[0].Tables[0] as Table;
Step 3: Delete the third row from the table.
table.Rows.RemoveAt(2);
Step 4: Delete the third column from the table.
for (int i = 0; i < table.Rows.Count; i++) { table.Rows[i].Cells.RemoveAt(2); }
Step 5: Save the document.
doc.SaveToFile("result.docx",FileFormat.docx2013);
Output:
Full code:
using Spire.Doc; namespace Delete_Rows_and_Columns { class Program { static void Main(string[] args) { Document doc = new Document(); doc.LoadFromFile("Sample.docx"); Table table = doc.Sections[0].Tables[0] as Table; table.Rows.RemoveAt(2); for (int i = 0; i < table.Rows.Count; i++) { table.Rows[i].Cells.RemoveAt(2); } doc.SaveToFile("result.docx",FileFormat.docx2013); } } }
Imports Spire.Doc Namespace Delete_Rows_and_Columns Class Program Private Shared Sub Main(args As String()) Dim doc As New Document() doc.LoadFromFile("Sample.docx") Dim table As Table = TryCast(doc.Sections(0).Tables(0), Table) table.Rows.RemoveAt(2) For i As Integer = 0 To table.Rows.Count - 1 table.Rows(i).Cells.RemoveAt(2) Next doc.SaveToFile("result.docx",FileFormat.docx2013); End Sub End Class End Namespace
C#/VB.NET: Insert or Extract Images from Tables in Word
A table in Microsoft Word can contain a variety of elements, including text, images, and many more. Sometimes, you may want to insert images into a table to present some information or extract images from a table for use in other documents. This article will teach you how to insert or extract images from tables in Word documents in C# and VB.NET using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Insert Images into a Table in a Word Document in C# and VB.NET
Spire.Doc provides the TableCell.Paragraphs[int].AppendPicture() method which enables you to add an image to a specific table cell. The detailed steps are as follows:
- Initialize an instance of the Document class.
- Load a Word document using Document.LoadFromFile() method.
- Get a specific section in the document by its index through Document.Sections[int] property.
- Get a specific table in the section by its index through Section.Tables[int] property.
- Access a specific cell to which you want to add an image through Table.Row[int].Cells[int] property.
- Add an image to a specific paragraph of the cell using TableCell.Paragraphs[int].AppendPicture() method.
- Set image width and height through DocPicture.Width and DocPicture.Height properties.
- Save the result document using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Fields; using System.Drawing; namespace InsertImagesIntoTable { class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document doc = new Document(); //Load a Word document doc.LoadFromFile("Table.docx"); //Get the first section of the document Section section = doc.Sections[0]; //Get the first table from the first section Table table = (Table)section.Tables[0]; //Add an image to the 3rd cell of the second row in the table TableCell cell = table.Rows[1].Cells[2]; DocPicture picture = cell.Paragraphs[0].AppendPicture(Image.FromFile("doc.png")); //Set image width and height picture.Width = 100; picture.Height = 100; //Add an image to the 3rd cell of the 3rd row in the table cell = table.Rows[2].Cells[2]; picture = cell.Paragraphs[0].AppendPicture(Image.FromFile("xls.png")); //Set image width and height picture.Width = 100; picture.Height = 100; //Save the result document doc.SaveToFile("AddImageToTable.docx", FileFormat.Docx2013); } } }
Extract Images from a Table in a Word Document in C# and VB.NET
To extract images from a table, you need to iterate through all rows in the tale, all cells in each row, all paragraphs in each cell and all child objects in each paragraph, then find the objects that are of DocPicture type and call DocPicture.Image.Save() method to save them to a specified file path. The detailed steps are as follows:
- Initialize an instance of the Document class.
- Load a Word document using Document.LoadFromFile() method.
- Get a specific section in the document by its index through Document.Sections[int] property.
- Get a specific table in the section by its index through Section.Tables[int] property.
- Iterate through all rows in the table.
- Iterate through all cells in each row.
- Iterate through all paragraphs in each cell.
- Iterate through all child objects in each paragraph.
- Check if the current child object is of DocPicture type.
- If the result is true, typecast the object as DocPicture and call DocPicture.Image.Save() method to save the image to a specified file path.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System; using System.Drawing.Imaging; namespace ExtractImagesFromTable { class Program { static void Main(string[] args) { //Initialize an instance of the Document class Document doc = new Document(); //Load a Word document doc.LoadFromFile("AddImageToTable.docx"); //Get the first section of the document Section section = doc.Sections[0]; //Get the first table from the first section Table table = (Table)section.Tables[0]; int index = 0; string imageName = null; //Iterate through all rows in the table for (int i = 0; i < table.Rows.Count; i++) { //Iterate through all cells in each row for (int j = 0; j < table.Rows[i].Cells.Count; j++) { //Iterate through all paragraphs in each cell foreach (Paragraph para in table[i, j].Paragraphs) { //Iterate through all child objects in each paragraph foreach (DocumentObject obj in para.ChildObjects) { //Check if the current child object is of DocPicture type if (obj is DocPicture) { //Save the images to a specified file path imageName = string.Format(@"images\TableImage-{0}.png", index); (obj as DocPicture).Image.Save(imageName, ImageFormat.Png); index++; } } } } } } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
How to Align a Table in C#
Usually there are three kinds of alignment style for a word table: left aligned, centered and right aligned. On Microsoft word, we can go to table properties to set the alignment for the whole table. Spire.Doc also offers a property table.TableFormat.HorizontalAlignment to enable developers to set the table alignment style easily in C#. This article will demonstrate how to align a table in C#.
Firstly, view the how to align a table for Microsoft word:
Here come to the code snippet of how Spire.Doc align a table.
Step 1: Create a word document and load from file.
Document doc = new Document(); doc.LoadFromFile("sample.docx");
Step 2: Get the first section and two tables from the word document.
Section section = doc.Sections[0]; Table table = section.Tables[0] as Table; Table table1 = section.Tables[1] as Table;
Step 3: Set the different alignment properties for each table.
table.TableFormat.HorizontalAlignment = RowAlignment.Right; table.TableFormat.LeftIndent = 34; table1.TableFormat.HorizontalAlignment = RowAlignment.Left; table1.TableFormat.LeftIndent = 34;
Step 4: Save the document to file:
doc.SaveToFile("result.docx", FileFormat.Docx);
Effective screenshots after align the table format:
Full codes:
using Spire.Doc; using Spire.Doc.Documents; namespace AlignTable { class Program { static void Main(string[] args) { Document doc = new Document(); doc.LoadFromFile("sample.docx"); Section section = doc.Sections[0]; Table table = section.Tables[0] as Table; Table table1 = section.Tables[1] as Table; table.TableFormat.HorizontalAlignment = RowAlignment.Right; table.TableFormat.LeftIndent = 34; table1.TableFormat.HorizontalAlignment = RowAlignment.Left; table1.TableFormat.LeftIndent = 34; doc.SaveToFile("result.docx", FileFormat.Docx); } } }
How to set the AutoFit option for word table in C#
When the contents in the word table are with the different length, the cell height of the word table will be changed and the whole table looks untidy. Microsoft Word offers AutoFit option to enable users to size a table automatically to make the word table looks beautiful. Spire.Doc also offers a method table.AutoFit() to make the AutoFit feature works well in C# for word table. This article will show you how to set the auto fit option in C# by using Spire.Doc.
Firstly, please view the Microsoft word's AutoFit feature.
View the code snippets of how to set the AutoFit option for Sprie.Doc.
Step 1: Create a word document and load from file.
Document doc = new Document(); doc.LoadFromFile("sample.docx");
Step 2: Get the first section and the first table from the word document.
Section section = doc.Sections[0]; Table table1 = section.Tables[0] as Table;
Step 3: Call the method AutoFit() to set the rule of the AutoFit option.
table1.AutoFit(AutoFitBehaviorType.AutoFitToContents);
Step 4: Save the document to file:
doc.SaveToFile("result.docx", FileFormat.Docx);
Effective screenshot:
Full codes:
using Spire.Doc; namespace SetAutofit { class Program { static void Main(string[] args) { Document doc = new Document(); doc.LoadFromFile("sample.docx"); Section section = doc.Sections[0]; Table table1 = section.Tables[0] as Table; table1.AutoFit(AutoFitBehaviorType.AutoFitToContents); doc.SaveToFile("result.docx", FileFormat.Docx); } } }