Buat Tabel

Aspose.Words memungkinkan pengguna membuat tabel dalam dokumen dari awal dan menyediakan beberapa metode berbeda untuk melakukannya. Artikel ini menyajikan detail tentang cara menambahkan tabel berformat ke dokumen Anda menggunakan setiap metode, serta perbandingan setiap metode di akhir artikel.

Gaya Tabel Default

Tabel yang baru dibuat diberi nilai default yang serupa dengan yang digunakan di Microsoft Word:

Properti Tabel Bawaan dalam Aspose.Words
Border Style Single
Border Width 1/2 pt
Warna Batas Black
Left and Right Padding 5.4 pts
AutoFit Mode AutoFit to Window
Allow AutoFit True

Buat Tabel dengan DocumentBuilder

Di Aspose.Words, pengguna dapat membuat tabel dalam dokumen menggunakan DocumentBuilder. Algoritma dasar untuk membuat tabel adalah sebagai berikut:

  1. Mulai tabel dengan StartTable
  2. Tambahkan sel ke tabel menggunakan InsertCell - ini secara otomatis memulai baris baru
  3. Secara opsional, gunakan properti CellFormat untuk menentukan pemformatan sel
  4. Sisipkan konten sel menggunakan metode DocumentBuilder yang sesuai seperti Writeln, InsertImage, dan lainnya
  5. Ulangi langkah 2-4 hingga baris selesai
  6. Panggil EndRow untuk mengakhiri baris saat ini
  7. Secara opsional, gunakan properti RowFormat untuk menentukan pemformatan baris
  8. Ulangi langkah 2-7 hingga tabel selesai
  9. Panggil EndTable untuk menyelesaikan pembuatan tabel

Proses pembuatan tabel dapat dilihat dengan jelas pada gambar berikut:

creating-table-process

Contoh kode berikut menunjukkan cara membuat tabel sederhana menggunakan DocumentBuilder dengan pemformatan default:

// 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");

Contoh kode berikut menunjukkan cara membuat tabel berformat menggunakan DocumentBuilder:

// 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");

Contoh kode berikut menunjukkan cara menyisipkan tabel bersarang menggunakan DocumentBuilder:

// 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");

Buat Tabel melalui DOM (Model Objek Dokumen)

Anda dapat menyisipkan tabel langsung ke DOM dengan menambahkan simpul Table baru pada posisi tertentu.

Harap dicatat bahwa segera setelah pembuatan simpul tabel, tabel itu sendiri akan benar-benar kosong, yaitu belum berisi baris dan sel. Untuk menyisipkan baris dan sel ke dalam tabel, tambahkan simpul turunan Row dan Cell yang sesuai ke DOM.

Contoh kode berikut menunjukkan cara membuat tabel baru dari awal dengan menambahkan simpul turunan yang sesuai ke pohon dokumen:

// 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");

Buat Tabel dari HTML

Aspose.Words mendukung penyisipan konten ke dalam dokumen dari sumber HTML menggunakan metode InsertHtml. Inputnya bisa berupa halaman HTML penuh atau hanya sebagian cuplikan.

Dengan menggunakan metode InsertHtml ini, pengguna dapat menyisipkan tabel ke dalam dokumen melalui tag tabel seperti <table>, <tr>, <td>.

Contoh kode berikut menunjukkan cara menyisipkan tabel ke dalam dokumen dari string yang berisi tag HTML:

// 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");

Menyisipkan Salinan Tabel yang Sudah Ada

Sering kali Anda perlu membuat tabel berdasarkan tabel yang sudah ada di dokumen. Cara termudah untuk menduplikasi tabel sambil mempertahankan semua pemformatan adalah dengan mengkloning simpul Tabel menggunakan metode deepClone.

Teknik yang sama dapat digunakan untuk menambahkan salinan baris atau sel yang ada ke tabel.

Contoh kode berikut menunjukkan cara menduplikasi tabel menggunakan konstruktor node:

// 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");

Contoh kode berikut menunjukkan cara mengkloning baris terakhir tabel dan menambahkannya ke tabel:

// 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");

Jika Anda ingin membuat tabel dalam dokumen yang berkembang secara dinamis dengan setiap catatan dari sumber data Anda, maka metode di atas tidak disarankan. Sebaliknya, keluaran yang diinginkan lebih mudah dicapai dengan menggunakan Mail merge dengan wilayah. Anda dapat mempelajari lebih lanjut tentang teknik ini di Mail Merge dengan Wilayah bagian.

Bandingkan Cara Membuat Tabel

Aspose.Words menyediakan beberapa metode untuk membuat tabel baru dalam dokumen. Setiap metode memiliki kelebihan dan kekurangannya masing-masing, sehingga pilihan yang akan digunakan seringkali bergantung pada situasi tertentu.

Mari kita lihat lebih dekat cara membuat tabel ini dan bandingkan pro dan kontranya:

Metode Keuntungan Kekurangan
Melalui DocumentBuilder Metode standar untuk menyisipkan tabel dan konten dokumen lainnya Terkadang sulit untuk membuat banyak variasi tabel secara bersamaan dengan instance builder yang sama
Melalui DOM Lebih cocok dengan kode di sekitarnya yang membuat dan menyisipkan node langsung ke DOM tanpa menggunakan DocumentBuilder Tabel dibuat “kosong”: sebelum melakukan sebagian besar operasi, Anda harus memanggil EnsureMinimum untuk membuat simpul turunan yang hilang
Dari HTML Dapat membuat tabel baru dari HTML sumber menggunakan tag seperti <table>, <tr>, <td> Tidak semua format tabel Microsoft Word yang memungkinkan dapat diterapkan ke HTML
Mengkloning tabel yang ada Anda dapat membuat salinan tabel yang ada dengan tetap mempertahankan semua pemformatan baris dan sel Node turunan yang sesuai harus dihapus sebelum tabel siap digunakan