Tablo Oluştur

Aspose.Words, kullanıcıların bir belgede sıfırdan tablolar oluşturmasına olanak tanır ve bunu yapmak için birkaç farklı yöntem sunar. Bu makale, her yöntemi kullanarak belgenize biçimlendirilmiş tabloları nasıl ekleyeceğinize ilişkin ayrıntıların yanı sıra makalenin sonunda her yöntemin karşılaştırmasını sunar.

Varsayılan Tablo Stilleri

Yeni oluşturulan tabloya Microsoft Word’te kullanılanlara benzer varsayılan değerler verilir:

Tablo Özelliği Aspose.Words’te varsayılan
Border Style Single
Border Width 1/2 pt
Border Color Black
Left and Right Padding 5.4 pts
AutoFit Mode AutoFit to Window
Allow AutoFit True

DocumentBuilder ile Tablo Oluşturma

Aspose.Words’te kullanıcılar DocumentBuilder‘yi kullanarak bir belgede tablo oluşturabilirler. Tablo oluşturmanın temel algoritması aşağıdaki gibidir:

  1. Tabloyu StartTable ile başlatın
  2. InsertCell‘i kullanarak tabloya bir hücre ekleyin; bu, otomatik olarak yeni bir satır başlatır
  3. İsteğe bağlı olarak hücre biçimlendirmesini belirtmek için CellFormat özelliğini kullanın
  4. Writeln, InsertImage ve diğerleri gibi uygun DocumentBuilder yöntemlerini kullanarak hücre içeriğini ekleyin
  5. Satır tamamlanana kadar 2-4. adımları tekrarlayın
  6. Geçerli satırı sonlandırmak için EndRow‘i arayın
  7. İsteğe bağlı olarak satır biçimlendirmesini belirtmek için RowFormat özelliğini kullanın
  8. Tablo tamamlanana kadar 2-7 arasındaki adımları tekrarlayın
  9. Tabloyu oluşturmayı tamamlamak için EndTable‘i arayın

Tablo oluşturma süreci aşağıdaki resimde açıkça görülebilir:

creating-table-process

Aşağıdaki kod örneği, varsayılan biçimlendirmeyle DocumentBuilder kullanarak basit bir tablonun nasıl oluşturulacağını gösterir:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Start building the table.
builder.StartTable();
builder.InsertCell();
builder.Write("Row 1, Cell 1 Content.");
// Build the second cell.
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content.");
// Call the following method to end the row and start a new row.
builder.EndRow();
// Build the first cell of the second row.
builder.InsertCell();
builder.Write("Row 2, Cell 1 Content");
// Build the second cell.
builder.InsertCell();
builder.Write("Row 2, Cell 2 Content.");
builder.EndRow();
// Signal that we have finished building the table.
builder.EndTable();
doc.Save(ArtifactsDir + "WorkingWithTables.CreateSimpleTable.docx");

Aşağıdaki kod örneği, DocumentBuilder kullanılarak biçimlendirilmiş bir tablonun nasıl oluşturulacağını gösterir:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.StartTable();
builder.InsertCell();
// Table wide formatting must be applied after at least one row is present in the table.
table.LeftIndent = 20.0;
// Set height and define the height rule for the header row.
builder.RowFormat.Height = 40.0;
builder.RowFormat.HeightRule = HeightRule.AtLeast;
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Name = "Arial";
builder.Font.Bold = true;
builder.CellFormat.Width = 100.0;
builder.Write("Header Row,\n Cell 1");
// We don't need to specify this cell's width because it's inherited from the previous cell.
builder.InsertCell();
builder.Write("Header Row,\n Cell 2");
builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Header Row,\n Cell 3");
builder.EndRow();
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.CellFormat.Width = 100.0;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
// Reset height and define a different height rule for table body.
builder.RowFormat.Height = 30.0;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.InsertCell();
// Reset font formatting.
builder.Font.Size = 12;
builder.Font.Bold = false;
builder.Write("Row 1, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content");
builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 1, Cell 3 Content");
builder.EndRow();
builder.InsertCell();
builder.CellFormat.Width = 100.0;
builder.Write("Row 2, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 2, Cell 2 Content");
builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 2, Cell 3 Content.");
builder.EndRow();
builder.EndTable();
doc.Save(ArtifactsDir + "WorkingWithTables.FormattedTable.docx");

Aşağıdaki kod örneği, DocumentBuilder kullanılarak iç içe tablonun nasıl ekleneceğini gösterir:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Cell cell = builder.InsertCell();
builder.Writeln("Outer Table Cell 1");
builder.InsertCell();
builder.Writeln("Outer Table Cell 2");
// This call is important to create a nested table within the first table.
// Without this call, the cells inserted below will be appended to the outer table.
builder.EndTable();
// Move to the first cell of the outer table.
builder.MoveTo(cell.FirstParagraph);
// Build the inner table.
builder.InsertCell();
builder.Writeln("Inner Table Cell 1");
builder.InsertCell();
builder.Writeln("Inner Table Cell 2");
builder.EndTable();
doc.Save(ArtifactsDir + "WorkingWithTables.NestedTable.docx");
view raw nested-table.cs hosted with ❤ by GitHub

DOM (Document Object Model) aracılığıyla Tablo Oluşturma

Belirli bir konuma yeni bir Table düğümü ekleyerek tabloları doğrudan DOM’e ekleyebilirsiniz.

Tablo düğümü oluşturulduktan hemen sonra tablonun tamamen boş olacağını, yani henüz satır ve hücre içermediğini lütfen unutmayın. Bir tabloya satır ve hücre eklemek için uygun Row ve Cell alt düğümlerini DOM’e ekleyin.

Aşağıdaki kod örneği, uygun alt düğümleri belge ağacına ekleyerek sıfırdan yeni bir tablonun nasıl oluşturulacağını gösterir:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
// We start by creating the table object. Note that we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
doc.FirstSection.Body.AppendChild(table);
// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid. In this case, a valid table should have at least one Row and one cell.
// Instead, we will handle creating the row and table ourselves.
// This would be the best way to do this if we were creating a table inside an algorithm.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));
row.AppendChild(cell);
// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));
// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);
doc.Save(ArtifactsDir + "WorkingWithTables.InsertTableDirectly.docx");

HTML’den Tablo Oluşturma

Aspose.Words, InsertHtml yöntemini kullanarak bir HTML kaynağından bir belgeye içerik eklenmesini destekler. Giriş, tam bir HTML sayfası veya yalnızca kısmi bir pasaj olabilir.

Kullanıcılar InsertHtml yöntemini kullanarak <table>, <tr>, <td> gibi tablo etiketleri aracılığıyla belgeye tablo ekleyebilirler.

Aşağıdaki kod örneği, HTML etiketlerini içeren bir dizeden belgeye tablonun nasıl ekleneceğini gösterir:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Note that AutoFitSettings does not apply to tables inserted from HTML.
builder.InsertHtml("<table>" +
"<tr>" +
"<td>Row 1, Cell 1</td>" +
"<td>Row 1, Cell 2</td>" +
"</tr>" +
"<tr>" +
"<td>Row 2, Cell 2</td>" +
"<td>Row 2, Cell 2</td>" +
"</tr>" +
"</table>");
doc.Save(ArtifactsDir + "WorkingWithTables.InsertTableFromHtml.docx");

Mevcut Bir Tablonun Kopyasını Ekleme

Çoğu zaman bir belgede zaten var olan bir tabloyu temel alarak bir tablo oluşturmanız gerekir. Tüm biçimlendirmeyi korurken bir tabloyu çoğaltmanın en kolay yolu, Clone yöntemini kullanarak Tablo düğümünü klonlamaktır.

Aynı teknik, mevcut bir satırın veya hücrenin kopyalarını bir tabloya eklemek için kullanılabilir.

Aşağıdaki kod örneği, düğüm oluşturucuları kullanılarak bir tablonun nasıl çoğaltılacağını gösterir:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Tables.docx");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
// Clone the table and insert it into the document after the original.
Table tableClone = (Table) table.Clone(true);
table.ParentNode.InsertAfter(tableClone, table);
// Insert an empty paragraph between the two tables,
// or else they will be combined into one upon saving this has to do with document validation.
table.ParentNode.InsertAfter(new Paragraph(doc), table);
doc.Save(ArtifactsDir + "WorkingWithTables.CloneCompleteTable.docx");

Aşağıdaki kod örneği, bir tablonun son satırının nasıl kopyalanacağını ve tabloya nasıl ekleneceğini gösterir:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Tables.docx");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
Row clonedRow = (Row) table.LastRow.Clone(true);
// Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into.
foreach (Cell cell in clonedRow.Cells)
cell.RemoveAllChildren();
table.AppendChild(clonedRow);
doc.Save(ArtifactsDir + "WorkingWithTables.CloneLastRow.docx");

Veri kaynağınızdaki her kayıtla dinamik olarak büyüyen bir belgede tablolar oluşturmayı düşünüyorsanız yukarıdaki yöntem önerilmez. Bunun yerine Mail merge’in bölgelerle birlikte kullanılmasıyla istenilen çıktı daha kolay elde edilir. Bu teknik hakkında daha fazla bilgiyi Bölgelerle Mail Merge bölümünde bulabilirsiniz.

Tablo Oluşturmanın Yollarını Karşılaştırın

Aspose.Words, bir belgede yeni tablolar oluşturmak için çeşitli yöntemler sağlar. Her yöntemin kendine özgü avantajları ve dezavantajları vardır, bu nedenle hangisinin kullanılacağının seçimi genellikle özel duruma bağlıdır.

Tablo oluşturmanın bu yollarına daha yakından bakalım ve bunların artılarını ve eksilerini karşılaştıralım:

Yöntem Avantajları Dezavantajları
DocumentBuilder aracılığıyla Tabloları ve diğer belge içeriğini eklemenin standart yöntemi Aynı oluşturucu örneğiyle aynı anda birçok tablo çeşidi oluşturmak bazen zor olabilir
DOM aracılığıyla DocumentBuilder kullanmadan düğümleri doğrudan DOM’e oluşturup ekleyen çevreleyen kodla daha iyi uyum sağlar Tablo “boş” olarak oluşturulmuştur: çoğu işlemi gerçekleştirmeden önce, eksik alt düğümleri oluşturmak için EnsureMinimum‘i çağırmanız gerekir
HTML’den <table>, <tr>, <td> gibi etiketleri kullanarak HTML kaynağından yeni bir tablo oluşturabilir Mümkün olan tüm Microsoft Word tablo formatları HTML’ye uygulanamaz
Mevcut bir tabloyu klonlama Tüm satır ve hücre biçimlendirmesini korurken mevcut bir tablonun bir kopyasını oluşturabilirsiniz Tablo kullanıma hazır olmadan önce uygun alt düğümlerin kaldırılması gerekir