Таблицы

  1. Добавьте SautinSoft.Document из Nuget.
  2. Создайте документ.
  3. Создайте таблицу.
  4. Сохраните документ.

Таблицы используются для упорядочивания содержимого документа и представления информации в строках и столбцах.


В этом примере кода мы создаем документ с таблицей из 5 строк и 5 столбцов.

Полный код

using SautinSoft.Document;
using SautinSoft.Document.Tables;

namespace Example
{
    class Program
    {
        private static DocumentCore dc;

        static void Main(string[] args)
        {
            // Get your free trial key here:   
            // https://sautinsoft.com/start-for-free/

            CreateTable();
        }

        /// <summary>
        /// Creates a new cell within a table and fills the it in staggered order.
        /// </summary>
        /// <param name="rowIndex">Row index.</param>
        /// <param name="colIndex">Column index.</param>
        /// <returns>New table cell.</returns>
        static TableCell NewCell(int rowIndex, int colIndex)
        {
            TableCell cell = new TableCell(dc);

            cell.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Black, 1);

            if (colIndex % 2 == 1 && rowIndex % 2 == 0 || colIndex % 2 == 0 && rowIndex % 2 == 1)
            {
                cell.CellFormat.BackgroundColor = Color.Black;
            }

            Run run = new Run(dc, string.Format("Row - {0}; Col - {1}", rowIndex, colIndex));
            run.CharacterFormat.FontColor = Color.Auto;

            cell.Blocks.Content.Replace(run.Content);

            return cell;
        }             

        /// <summary>
        /// Creates a new document with a table.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/tables.php
        /// </remarks>
        static void CreateTable()
        {
            dc = new DocumentCore();           

            string filePath = @"Result-file.docx";

            Table table = new Table(dc, 5, 5, NewCell);

            // Place the 'Table' at the start of the 'Document'.
            // By the way, we didn't create a 'Section' in our document.
            // As we're using 'Content' property, a 'Section' will be created automatically if necessary.
            dc.Content.Start.Insert(table.Content);
            dc.Save(filePath);

            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true });
        }
    }
}

Download

Imports SautinSoft.Document
Imports SautinSoft.Document.Tables

Namespace Example
    Friend Class Program
        Private Shared dc As DocumentCore

        Shared Sub Main(ByVal args() As String)
            CreateTable()
        End Sub
        ''' Get your free trial key here:   
        ''' https://sautinsoft.com/start-for-free/
        ''' <summary>
        ''' Creates a new cell within a table and fills the it in staggered order.
        ''' </summary>
        ''' <param name="rowIndex">Row index.</param>
        ''' <param name="colIndex">Column index.</param>
        ''' <returns>New table cell.</returns>
        Public Shared Function NewCell(ByVal rowIndex As Integer, ByVal colIndex As Integer) As TableCell
            Dim cell As New TableCell(dc)

            cell.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Black, 1)

            If colIndex Mod 2 = 1 AndAlso rowIndex Mod 2 = 0 OrElse colIndex Mod 2 = 0 AndAlso rowIndex Mod 2 = 1 Then
                cell.CellFormat.BackgroundColor = Color.Black
            End If

            Dim run As New Run(dc, String.Format("Row - {0}; Col - {1}", rowIndex, colIndex))
            run.CharacterFormat.FontColor = Color.Auto

            cell.Blocks.Content.Replace(run.Content)

            Return cell
        End Function

        ''' <summary>
        ''' Creates a new document with a table.
        ''' </summary>
        ''' <remarks>
        ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/tables.php
        ''' </remarks>
        Public Shared Sub CreateTable()
            dc = New DocumentCore()

            Dim filePath As String = "Result-file.docx"

            Dim table As New Table(dc, 5, 5, AddressOf NewCell)

            ' Place the 'Table' at the start of the 'Document'.
            ' By the way, we didn't create a 'Section' in our document.
            ' As we're using 'Content' property, a 'Section' will be created automatically if necessary.
            dc.Content.Start.Insert(table.Content)
            dc.Save(filePath)

            System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(filePath) With {.UseShellExecute = True})
        End Sub
    End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



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

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