У цьому посібнику описано два різні способи створення таблиці в документі Word за допомогою C#. Спочатку ми створимо таблицю в Word за допомогою C# за допомогою Aspose DocumentBuilder, а пізніше створимо таблицю Word за допомогою C# безпосередньо в об’єктній моделі документа Word (DOM).
Кроки для створення таблиці в документі Word за допомогою C#
- Посилання на пакет Aspose.Words for .NET із NuGet у рішенні
- Імпортуйте простори імен Aspose.Words і Aspose.Words.Tables
- Створіть екземпляр класу DocumentBuilder або Table
- Використовуйте метод InsertCell або Table.Rows.Cells.Add, щоб додати клітинки в рядок таблиці
- Щоб вставити текст абзацу, використовуйте метод DocumentBuilder.Write або Cell.AppendChild
- Створіть кілька рядків у таблиці та завершіть створення таблиці в документі Word
- Зберегти як документ Word з таблицею у форматі DOCX на диску
Наступний приклад коду Aspose DocumentBuilder можна використовувати в програмі .NET для створення таблиць C# Word.
Код для створення таблиці в документі Word за допомогою C#
using Aspose.Words; | |
using Aspose.Words.Tables; | |
namespace CreateTableInWordDocumentUsingCsharp | |
{ | |
class CreateTableWord | |
{ | |
static void Main(string[] args) | |
{ | |
// Set license before C# Word table creation | |
License setupToCreateTable = new License(); | |
setupToCreateTable.SetLicense(@"license file path.lic"); | |
// Document Builder object to create Table in Word document | |
DocumentBuilder toCreateTableInWord = new DocumentBuilder(); | |
// Mark the start of Word Table | |
Table tableInWord = toCreateTableInWord.StartTable(); | |
// Insert a new Row & then first Cell in Word Table | |
toCreateTableInWord.InsertCell(); | |
// Write text in Table Cell | |
toCreateTableInWord.Write("Table Row 1 and Cell 1"); | |
// Insert a new Cell in same Word Table Row | |
toCreateTableInWord.InsertCell(); | |
// Insert an Image in Word Table Cell | |
toCreateTableInWord.InsertImage("insert image in word table.jpg"); | |
// Mark the end of Table Row | |
toCreateTableInWord.EndRow(); | |
// Mark end of Word Table creation | |
toCreateTableInWord.EndTable(); | |
// Save Word DOCX document with Table on disk | |
toCreateTableInWord.Document.Save("c# word table created in.docx"); | |
} | |
} | |
} |
По суті, ця програма для створення таблиці Word C# дозволяє вставляти таблицю в документ Word. Спочатку він додає дві клітинки в перший рядок таблиці, а потім записує текстовий вміст у першу клітинку, а потім додати зображення до Word C# останню клітинку.
Код для створення таблиці Word за допомогою C# (класи DOM)
using Aspose.Words; | |
using Aspose.Words.Tables; | |
namespace CreateWordTable | |
{ | |
class CreateTableInWord | |
{ | |
static void Main(string[] args) | |
{ | |
// Set license before creating Word table | |
License license = new License(); | |
license.SetLicense(@"license file path.lic"); | |
Document wordDocument = new Document(); // Create empty Word document | |
Table wordTable = new Table(wordDocument); // Create Table object | |
wordTable.Rows.Add(new Row(wordDocument)); // Create a Row inside Table | |
wordTable.FirstRow.Cells.Add(new Cell(wordDocument)); // Create a single Cell in Table Row | |
wordTable.FirstRow.FirstCell.AppendChild(new Paragraph(wordDocument)); // Add a Paragraph inside Cell | |
// Write text content inside Word Table Cell | |
wordTable.FirstRow.FirstCell.FirstParagraph.Runs.Add(new Run(wordDocument, "Text in Table Row 1 and Cell 1")); | |
// Insert Table at the end of Word Document | |
wordDocument.FirstSection.Body.InsertBefore(wordTable, wordDocument.FirstSection.Body.LastParagraph); | |
// Save Word document to DOCX format | |
wordDocument.Save("c# word table created in.docx"); | |
} | |
} | |
} |
Наведений вище приклад коду Aspose Word для створення таблиці C# просто представляє альтернативний підхід до додавання елемента таблиці в об’єктну модель документа Word за допомогою класів Table, Row, Cell і Paragraph.