Использование DocumentBuilder для вставки таблицы на C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Создайте новый документ.
  3. Создайте конструктор на основе документа.
  4. Используйте StartTable, InsertCell, endRow для добавления данных таблицы.

Основной алгоритм создания таблицы с помощью DocumentBuilder прост:


                    DocumentCore dc = new DocumentCore();
                    DocumentBuilder db = new DocumentBuilder(dc);
                
  1. Начало таблицы, используя db.StartTable.
    Table table = db.StartTable();
  2. Вставьте ячейку с помощью db.InsertCell. Это автоматически запускает новую строку. При необходимости используйте свойство db.CellFormat, чтобы указать форматирование ячейки.
  3. Вставка содержимого ячейки с помощью методов DocumentBuilder.
  4. Повторяйте шаги, пока ряд не будет завершен.
  5. Вызовите db.EndRow, чтобы завершить текущую строку. При необходимости используйте свойство db.RowFormat для указания форматирования строки.
  6. Повторяйте шаги, пока таблица не будет заполнена.
  7. Вызовите db.EndTable, чтобы завершить построение таблицы. Соответствующие методы создания таблицы DocumentBuilder описаны ниже.

Начало таблицы

Вызов db.StartTable — это первый шаг в построении таблицы. Его также можно вызвать внутри ячейки, в этом случае он запускает вложенную таблицу. Следующий вызываемый метод — db.InsertCell.

Вставка ячейки

После вызова db.InsertCell создается новая ячейка, и любое содержимое, которое Вы добавляете с помощью других методов класса DocumentBuilder, будет добавлено в текущую ячейку. Чтобы создать новую ячейку в той же строке, снова вызовите db.InsertCell. Используйте свойство db.CellFormat, чтобы указать форматирование ячейки.

Завершение строки

Вызовите db.EndRow, чтобы закончить текущую строку. Если Вы вызовете db.InsertCell сразу после этого, таблица продолжится с новой строки. Используйте свойство db.RowFormat, чтобы задать форматирование строки.

Завершение таблицы

Вызовите db.EndTable, чтобы завершить текущую таблицу. Этот метод следует вызывать только один раз после вызова db.EndRow. При вызове db.EndTable перемещает курсор из текущей ячейки в положение сразу после таблицы. В следующем примере показано, как создать форматированную таблицу, содержащую 3 строки и 3 столбца.


Полный код

using System;
using SautinSoft.Document;
using SautinSoft.Document.Tables;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            InsertingTable();
        }
        /// <summary>
        /// Creates a table using DocumentBuilder and saves it in a desired format.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/documentbuilder-inserting-table.php
        /// </remarks>

        static void InsertingTable()
        {
            DocumentCore dc = new DocumentCore();
            DocumentBuilder db = new DocumentBuilder(dc);

            // Create a new table with preferred width.
            Table table = db.StartTable();
            db.TableFormat.PreferredWidth = new TableWidth(LengthUnitConverter.Convert(5, LengthUnit.Inch, LengthUnit.Point), TableWidthUnit.Point);

            // Specify formatting of cells and alignment.
            db.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Green, 1);
            db.CellFormat.VerticalAlignment = VerticalAlignment.Top;
            db.ParagraphFormat.Alignment = HorizontalAlignment.Center;

            // Specify height of rows and write text.
            db.RowFormat.Height = new TableRowHeight(105f, HeightRule.Exact);
            db.InsertCell();
            db.Write("This is Row 1 Cell 1");
            db.InsertCell();
            db.Write("This is Row 1 Cell 2");
            db.InsertCell();
            db.Write("This is Row 1 Cell 3");
            db.EndRow();

            // Specify formatting of cells and alignment.
            db.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Black, 1);
            db.CellFormat.VerticalAlignment = VerticalAlignment.Center;
            db.ParagraphFormat.Alignment = HorizontalAlignment.Left;

            // Specify height of rows and write text.
            db.RowFormat.Height = new TableRowHeight(150f, HeightRule.Exact);
            db.InsertCell();
            db.Write("This is Row 2 Cell 1");
            db.InsertCell();
            db.Write("This is Row 2 Cell 2");
            db.InsertCell();
            db.Write("This is Row 2 Cell 3");
            db.EndRow();

            // Specify formatting of cells and alignment.
            db.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Orange, 1);
            db.CellFormat.VerticalAlignment = VerticalAlignment.Bottom;
            db.ParagraphFormat.Alignment = HorizontalAlignment.Right;

            // Specify height of rows and write text
            db.RowFormat.Height = new TableRowHeight(125f, HeightRule.Exact);
            db.InsertCell();
            db.Write("This is Row 3 Cell 1");
            db.InsertCell();
            db.Write("This is Row 3 Cell 2");
            db.InsertCell();
            db.Write("This is Row 3 Cell 3");
            db.EndRow();
            db.EndTable();

            // Save our document into DOCX format.
            string filePath = "Result.docx";
            dc.Save(filePath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true });
        }
    }
}

Download

Imports System
Imports SautinSoft.Document
Imports SautinSoft.Document.Tables
Imports System.Collections.Generic

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			InsertingTable()
		End Sub
                ''' Get your free 30-day key here:   
                ''' https://sautinsoft.com/start-for-free/
		''' <summary>
		''' Creates a table using DocumentBuilder and saves it in a desired format.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/documentbuilder-inserting-table.php
		''' </remarks>

		Private Shared Sub InsertingTable()
			Dim dc As New DocumentCore()
			Dim db As New DocumentBuilder(dc)

			' Create a new table with preferred width.
			Dim table As Table = db.StartTable()
			db.TableFormat.PreferredWidth = New TableWidth(LengthUnitConverter.Convert(5, LengthUnit.Inch, LengthUnit.Point), TableWidthUnit.Point)

			' Specify formatting of cells and alignment.
			db.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Green, 1)
			db.CellFormat.VerticalAlignment = VerticalAlignment.Top
			db.ParagraphFormat.Alignment = HorizontalAlignment.Center

			' Specify height of rows and write text.
			db.RowFormat.Height = New TableRowHeight(105.0F, HeightRule.Exact)
			db.InsertCell()
			db.Write("This is Row 1 Cell 1")
			db.InsertCell()
			db.Write("This is Row 1 Cell 2")
			db.InsertCell()
			db.Write("This is Row 1 Cell 3")
			db.EndRow()

			' Specify formatting of cells and alignment.
			db.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Black, 1)
			db.CellFormat.VerticalAlignment = VerticalAlignment.Center
			db.ParagraphFormat.Alignment = HorizontalAlignment.Left

			' Specify height of rows and write text.
			db.RowFormat.Height = New TableRowHeight(150.0F, HeightRule.Exact)
			db.InsertCell()
			db.Write("This is Row 2 Cell 1")
			db.InsertCell()
			db.Write("This is Row 2 Cell 2")
			db.InsertCell()
			db.Write("This is Row 2 Cell 3")
			db.EndRow()

			' Specify formatting of cells and alignment.
			db.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Orange, 1)
			db.CellFormat.VerticalAlignment = VerticalAlignment.Bottom
			db.ParagraphFormat.Alignment = HorizontalAlignment.Right

			' Specify height of rows and write text
			db.RowFormat.Height = New TableRowHeight(125.0F, HeightRule.Exact)
			db.InsertCell()
			db.Write("This is Row 3 Cell 1")
			db.InsertCell()
			db.Write("This is Row 3 Cell 2")
			db.InsertCell()
			db.Write("This is Row 3 Cell 3")
			db.EndRow()
			db.EndTable()

			' Save our document into DOCX format.
			Dim filePath As String = "Result.docx"
			dc.Save(filePath)

			' Open the result for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(filePath) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.