When creating a word table, we may want to add some common elements such as text and pictures into it. In the sample given below, we will demonstrate how to add pictures to specified table cells in a word document using Spire.Doc for .NET.
Spire.Doc for .NET provides developers a class named TableCollection which contains a Tables property to help developers access specified table, and then add pictures to the table cells by invoking public DocPicture Paragraph.AppendPicture(Image image) method.
Detail steps and code snippets are as following:
Use namespace:
using System.Drawing; using Spire.Doc; using Spire.Doc.Fields;
Step 1: Initialize a new instance of Document class and load the sample word file.
Document document = new Document(); document.LoadFromFile("Sample.docx");
Step 2: Get the first table from the first section of the document.
Table table1 = (Table)document.Sections[0].Tables[0];
Step 3: Call the Paragraph.AppendPicture(Image image) method to add pictures to the specified table cells, then set width and height of the pictures.
DocPicture picture = table1.Rows[1].Cells[2].Paragraphs[0].AppendPicture(Image.FromFile("Pic1.png")); picture.Width = 100; picture.Height = 100; picture = table1.Rows[2].Cells[2].Paragraphs[0].AppendPicture(Image.FromFile("Pic2.png")); picture.Width = 100; picture.Height = 100;
Step 4: Save and launch the file.
document.SaveToFile("Result.docx",FileFormat.docx2013); System.Diagnostics.Process.Start("Result.docx");
Please see the result word table after adding pictures:
Full codes:
using Spire.Doc; using Spire.Doc.Fields; namespace AlignTable { class Program { static void Main(string[] args) { Document document = new Document(); document.LoadFromFile("Sample.docx"); Table table1 = (Table)document.Sections[0].Tables[0]; DocPicture picture = table1.Rows[1].Cells[2].Paragraphs[0].AppendPicture(Image.FromFile("Pic1.png")); picture.Width = 100; picture.Height = 100; picture = table1.Rows[2].Cells[2].Paragraphs[0].AppendPicture(Image.FromFile("Pic2.png")); picture.Width = 100; picture.Height = 100; document.SaveToFile("Result.docx"); System.Diagnostics.Process.Start("Result.docx"); } } }
Imports Spire.Doc Imports Spire.Doc.Fields Namespace AlignTable Class Program Private Shared Sub Main(args As String()) Dim document As New Document() document.LoadFromFile("Sample.docx") Dim table1 As Table = DirectCast(document.Sections(0).Tables(0), Table) Dim picture As DocPicture = table1.Rows(1).Cells(2).Paragraphs(0).AppendPicture(Image.FromFile("Pic1.png")) picture.Width = 100 picture.Height = 100 picture = table1.Rows(2).Cells(2).Paragraphs(0).AppendPicture(Image.FromFile("Pic2.png")) picture.Width = 100 picture.Height = 100 document.SaveToFile("Result.docx") System.Diagnostics.Process.Start("Result.docx") End Sub End Class End Namespace