Bir Tablo Oluşturun

Aspose.Words kullanıcıların bir belge içinde sıfırdan tablolar oluşturmasına olanak tanır ve bunu yapmak için birçok farklı yöntem sağlar. Bu makale her bir yöntem kullanarak belgenize biçimlendirilmiş tablolar ekleme hakkında ayrıntılar sunar ve makalenin sonunda her yöntemi karşılaştırır.

Varsayılan Tablo stilleri

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

Tablo Özelliği Varsayılan Aspose.Words
Border Style Single
Border Width 1/2 pt
Sınır Rengi Black
Left and Right Padding 5.4 pts
AutoFit Mode AutoFit to Window
Allow AutoFit True

DocumentBuilder ile Tablo Oluşturun

B Aspose.Words, kullanıcılar bir belge içinde bir tablo oluşturmak için DocumentBuilder kullanabilir. Bir tablo oluşturmak için temel algoritma şöyledir:

  1. Masayı StartTable ile başlatın
  2. Tabloya bir hücre eklemek için InsertCell – bu otomatik olarak yeni bir satır başlatır
  3. İsteğe bağlı olarak, hücre biçimlendirmesi belirtmek için CellFormat özelliğini kullanın
  4. Cell içeriğini uygun DocumentBuilder yöntemleriyle yerleştirin örneğin Writeln, InsertImage ve diğerleri
  5. 2-4 adımları tekrarlayın, satır tamamlanana kadar
  6. Çağrı EndRow geçerli satırı sonlandırmak için
  7. İsteğe bağlı olarak, " RowFormat" özelliğini satır biçimlendirmesini belirtmek için kullanın
  8. 2-7 adım tekrarlayın, tablo tamamlanana kadar
  9. Tablo oluşturmayı tamamlamak için EndTable çağırın

Bir tablo oluşturma işlemi aşağıdaki resimde açıkça görülmektedir:

creating-table-process

Aşağıdaki kod örneği, varsayılan biçimlendirmeyi kullanarak bir tablo oluşturmak için DocumentBuilder nasıl kullanılacağını göstermektedir:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.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(getArtifactsDir() + "WorkingWithTables.CreateSimpleTable.docx");

Aşağıdaki kod örneği, DocumentBuilder kullanarak bir biçimlendirilmiş tablo oluşturmayı gösterir

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.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.setLeftIndent(20.0);
// Set height and define the height rule for the header row.
builder.getRowFormat().setHeight(40.0);
builder.getRowFormat().setHeightRule(HeightRule.AT_LEAST);
builder.getCellFormat().getShading().setBackgroundPatternColor(new Color((198), (217), (241)));
builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
builder.getFont().setSize(16.0);
builder.getFont().setName("Arial");
builder.getFont().setBold(true);
builder.getCellFormat().setWidth(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.getCellFormat().setWidth(200.0);
builder.write("Header Row,\n Cell 3");
builder.endRow();
builder.getCellFormat().getShading().setBackgroundPatternColor(Color.WHITE);
builder.getCellFormat().setWidth(100.0);
builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
// Reset height and define a different height rule for table body.
builder.getRowFormat().setHeight(30.0);
builder.getRowFormat().setHeightRule(HeightRule.AUTO);
builder.insertCell();
// Reset font formatting.
builder.getFont().setSize(12.0);
builder.getFont().setBold(false);
builder.write("Row 1, Cell 1 Content");
builder.insertCell();
builder.write("Row 1, Cell 2 Content");
builder.insertCell();
builder.getCellFormat().setWidth(200.0);
builder.write("Row 1, Cell 3 Content");
builder.endRow();
builder.insertCell();
builder.getCellFormat().setWidth(100.0);
builder.write("Row 2, Cell 1 Content");
builder.insertCell();
builder.write("Row 2, Cell 2 Content");
builder.insertCell();
builder.getCellFormat().setWidth(200.0);
builder.write("Row 2, Cell 3 Content.");
builder.endRow();
builder.endTable();
doc.save(getArtifactsDir() + "WorkingWithTables.FormattedTable.docx");

Aşağıdaki kod örneği, bir alt tablonun nasıl ekleneceğini gösterir. DocumentBuilder kullanarak:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.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.getFirstParagraph());
// Build the inner table.
builder.insertCell();
builder.writeln("Inner Table Cell 1");
builder.insertCell();
builder.writeln("Inner Table Cell 2");
builder.endTable();
doc.save(getArtifactsDir() + "WorkingWithTables.NestedTable.docx");

Bir tablo oluşturun DOM (Document Object Model) aracılığıyla

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

Lütfen unutmayın ki tablo düğüm oluşturma hemen ardından, tablo tamamen boş olacaktır, yani henüz satır ve hücreler içermez. Bir tabloya satır ve hücre eklemek için, uygun Row ve Cell alt düğümleri DOM’e ekleyin.

Aşağıdaki kod örneği, bir belge ağacına uygun alt düğümler ekleyerek sıfırdan yeni bir tablo oluşturmayı gösterir:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.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.getFirstSection().getBody().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.getRowFormat().setAllowBreakAcrossPages(true);
table.appendChild(row);
// We can now apply any auto fit settings.
table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);
Cell cell = new Cell(doc);
cell.getCellFormat().getShading().setBackgroundPatternColor(Color.BLUE);
cell.getCellFormat().setWidth(80.0);
cell.appendChild(new Paragraph(doc));
cell.getFirstParagraph().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.deepClone(false));
row.getLastCell().appendChild(new Paragraph(doc));
row.getLastCell().getFirstParagraph().appendChild(new Run(doc, "Row 1, Cell 2 Text"));
doc.save(getArtifactsDir() + "WorkingWithTables.InsertTableDirectly.docx");

HTML’den Tablo Oluştur

Bir belgeden bir HTML kaynağı kullanılarak içeriği eklemek için InsertHtml‘u kullanan Aspose.Words destekler. Giriş, bir tam HTML sayfası veya sadece kısmi bir parçacıktan oluşabilir.

Bu InsertHtml yöntemini kullanarak kullanıcılar tablo etiketleri aracılığıyla belgeye tablo girebilirler. <table>, <tr>, <td>

Aşağıdaki kod örneği, bir belgeye bir HTML etiketi içeren bir dizeden tablo eklemeyi gösterir:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.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(getArtifactsDir() + "WorkingWithTables.InsertTableFromHtml.docx");

Mevcut Bir Tablonun Bir Kopiasını Ekle

Bir belgedeki zaten var olan bir tablodan dayalı bir tablo oluşturmanız gerektiğinde sık sık zamanlar vardır. Tablo biçimlendirmesini koruyarak bir tablonun kolayca çoğaltılmasının en kolay yolu, deepClone yöntemi kullanılarak Tablo düğümünü kopyalamaktır.

Bu tekniği mevcut bir satır ya da hücrenin kopyalarını bir tabloya eklemek için kullanılabilir.

Aşağıdaki kod örneği düğüm oluşturucular kullanarak bir tabloyu nasıl çoğaltacağınızı göstermektedir:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document(getMyDir() + "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.deepClone(true);
table.getParentNode().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.getParentNode().insertAfter(new Paragraph(doc), table);
doc.save(getArtifactsDir() + "WorkingWithTables.CloneCompleteTable.docx");

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document(getMyDir() + "Tables.docx");
Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
Row clonedRow = (Row) table.getLastRow().deepClone(true);
// Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into.
for (Cell cell : (Iterable<Cell>) clonedRow.getCells())
cell.removeAllChildren();
table.appendChild(clonedRow);
doc.save(getArtifactsDir() + "WorkingWithTables.CloneLastRow.docx");

Verilerinizden gelen her kayıtla birlikte dinamik olarak büyüyen bir belge içinde tablolar oluşturmayı düşünüyorsanız, yukarıdaki yöntem tavsiye edilmez. Bunun yerine, istenilen çıktı daha kolay Mail merge ile bölgelerin kullanılması ile elde edilir. Bu tekniği hakkında daha fazla bilgi Mail Merge with Regions‘daki bölümde edinebilirsiniz.

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

Aspose.Words bir belge içinde yeni tablolar oluşturmak için birkaç yöntem sağlar. Her yöntemin kendi avantajları ve dezavantajları vardır, bu nedenle hangi yöntemi kullanacağına karar vermek genellikle spesifik duruma bağlıdır.

Masaları oluşturmak için bu yöntemlere daha yakından bakalım ve avantajlarını ve dezavantajlarını karşılaştıralım:

Yöntem Avantajlar Dezavantajlar
Via DocumentBuilder Tablolar ve diğer belge içeriği eklemek için standart yöntem Aynı anda aynı yapı örneğiyle birçok çeşit tablo oluşturmak zor olabilir
Via DOM Çevreleyen kodun içine doğrudan DOM’e düğüm ekleyerek bir DocumentBuilder kullanmadan daha iyi uyum sağlar Tablo oluşturulur “boş”: çoğu işlemi gerçekleştirmeden önce, eksik olan alt düğümleri oluşturmak için EnsureMinimum‘ı çağırmanız gerekir
HTML’den Can create a new table from HTML source using tags like <table>, <tr>, <td> Tüm olası Microsoft Word tablo biçimleri HTML’e uygulanamaz
Mevcut bir tablonun kopyalanması Varolan bir tabloya tüm satır ve hücre biçimlendirmesini koruyarak bir kopyasını oluşturabilirsiniz Masa kullanıma hazır hale gelmeden önce uygun alt düğümler kaldırılmalıdır