Hướng dẫn từng bước ngắn gọn này trình bày cách tạo bảng trong Tài liệu Word bằng Java. Với sự trợ giúp của hướng dẫn này, bạn có thể chèn một hoặc nhiều bảng để sắp xếp thông tin theo yêu cầu của mình. Ở bước cuối cùng, tệp đầu ra được lưu dưới dạng tệp DOCX nhưng bạn có thể lưu nó ở bất kỳ định dạng tệp Word nào.
Các bước để tạo bảng trong tài liệu Word bằng Java
- Thêm Aspose.Words for Java từ kho lưu trữ Maven
- Khởi tạo một tài liệu Word trống bằng lớp Document
- Khởi tạo một phiên bản lớp Table mới
- Tạo một Row mới trong bảng
- Tạo một ô và thêm một đoạn mới bên trong ô
- Chèn bảng vào cuối tài liệu
- Lưu tài liệu Word với Bảng dưới dạng tệp DOCX
Sử dụng các bước này, chúng ta có thể chèn bảng vào tài liệu Word bằng Java. Chúng ta có thể thêm thông tin vào các ô và sắp xếp nội dung tài liệu theo chương trình bằng cách sử dụng Java.
Mã để tạo bảng trong tài liệu Word bằng Java
import com.aspose.words.Cell; | |
import com.aspose.words.Document; | |
import com.aspose.words.License; | |
import com.aspose.words.Paragraph; | |
import com.aspose.words.Row; | |
import com.aspose.words.Run; | |
import com.aspose.words.Table; | |
public class CreateTableInWordUsingJava | |
{ | |
public static void main(String[] args) throws Exception { //main function for CreateTableInWordUsingJava class | |
// Initialize a license to avoid trial version watermark in the output Word file after adding comments | |
License license = new License(); | |
license.setLicense("Aspose.Words.lic"); | |
// Initialize a blank Word document using Document class | |
Document wordDocument = new Document(); | |
// Initialize a new Table class instance | |
Table wordTable = new Table(wordDocument); | |
// Create a new Row in the Table | |
wordTable.getRows().add(new Row(wordDocument)); | |
// Create single Cell in the Table Row | |
wordTable.getFirstRow().getCells().add(new Cell(wordDocument)); | |
// Add a new Paragraph inside Cell | |
wordTable.getFirstRow().getFirstCell().appendChild(new Paragraph(wordDocument)); | |
// Add text content inside the Table Cell | |
wordTable.getFirstRow().getFirstCell().getFirstParagraph().getRuns().add(new Run(wordDocument, "Text in Table Row 1 and Cell 1")); | |
// Insert a Table at the last portion of Word Document | |
wordDocument.getFirstSection().getBody().insertBefore(wordTable, wordDocument.getFirstSection().getBody().getLastParagraph()); | |
// Save Word document with Table in DOCX format | |
wordDocument.save("word_table.docx"); | |
} | |
} |
Trong mã Java này, chúng tôi đã khởi tạo một Tài liệu Word trống, sau đó thêm Bảng và chèn nội dung vào một ô cụ thể. Sau đó, bảng được chèn vào cuối để trình bày cách tạo bảng trong tài liệu Word bằng Java.
Trong hướng dẫn này, chúng ta đã học cách chèn bảng vào tài liệu Word bằng Java. Tuy nhiên, nếu bạn muốn thêm hàng vào bảng trong tài liệu Word thì bạn có thể tham khảo bài viết cách thêm hàng vào bảng trong DOCX bằng Java.