Xây dựng một Bảng từ DataTable
Hầu hết các ứng dụng sẽ lấy dữ liệu từ một cơ sở dữ liệu và lưu trữ chúng trong hình thức của một DataTable. Bạn có thể muốn dễ dàng chèn dữ liệu này vào tài liệu của bạn dưới dạng một bảng mới và nhanh chóng áp dụng định dạng cho toàn bộ bảng.
Sử dụng Aspose.Words, bạn có thể dễ dàng lấy dữ liệu từ một cơ sở dữ liệu và lưu trữ nó dưới dạng bảng:
- Tạo một đối tượng mới DocumentBuilder trên Document của bạn.
- Khởi tạo một bảng mới bằng cách sử dụng DocumentBuilder.
- Nếu chúng ta muốn chèn tên của mỗi cột từ DataTable là hàng tiêu đề thì lặp lại qua từng cột dữ liệu và viết tên cột vào một hàng trong bảng.
- Đi qua từng DataRow trong DataTable:
- Đi qua từng đối tượng trong DataRow.
- Chèn đối tượng vào tài liệu bằng cách sử dụng DocumentBuilder. Phương pháp được dùng phụ thuộc vào loại đối tượng đang được chèn ví dụ [DocumentBuilder.writeln()](https://reference.aspose.com/words/java/com.aspose.words/documentbuilder/#writeln() cho văn bản và [DocumentBuilder.insertImage()](https://reference.aspose.com/words/java/com.aspose.words/documentbuilder/#insertImage(byte[]) cho một mảng byte đại diện cho hình ảnh.
- Kết thúc xử lý của hàng dữ liệu cũng kết thúc dòng đang được tạo bởi DocumentBuilder bằng cách sử dụng DocumentBuilder.endRow().
- Một khi đã xử lý tất cả các hàng từ DataTable hãy kết thúc bảng bằng cách gọi DocumentBuilder.endTable().
- Cuối cùng, chúng ta có thể thiết lập kiểu bảng mong muốn bằng cách sử dụng một trong các thuộc tính bảng phù hợp như Table.getStyleIdentifier() để tự động áp dụng định dạng cho toàn bộ bảng. Cụm dữ liệu sau trong DataTable được dùng trong ví dụ này:
Mã ví dụ sau đây cho thấy cách thực hiện thuật toán ở trên trong Aspose.Words:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
/// <summary> | |
/// Imports the content from the specified DataTable into a new Aspose.Words Table object. | |
/// The table is inserted at the document builder's current position and using the current builder's formatting if any is defined. | |
/// </summary> | |
public Table importTableFromDataTable(DocumentBuilder builder, DataTable dataTable, | |
boolean importColumnHeadings) | |
{ | |
Table table = builder.startTable(); | |
// Check if the columns' names from the data source are to be included in a header row. | |
if (importColumnHeadings) | |
{ | |
// Store the original values of these properties before changing them. | |
boolean boldValue = builder.getFont().getBold(); | |
int paragraphAlignmentValue = builder.getParagraphFormat().getAlignment(); | |
// Format the heading row with the appropriate properties. | |
builder.getFont().setBold(true); | |
builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER); | |
// Create a new row and insert the name of each column into the first row of the table. | |
for (DataColumn column : dataTable.getColumns()) | |
{ | |
builder.insertCell(); | |
builder.writeln(column.getColumnName()); | |
} | |
builder.endRow(); | |
// Restore the original formatting. | |
builder.getFont().setBold(boldValue); | |
builder.getParagraphFormat().setAlignment(paragraphAlignmentValue); | |
} | |
for (DataRow dataRow : (Iterable<DataRow>) dataTable.getRows()) | |
{ | |
for (Object item : dataRow.getItemArray()) | |
{ | |
// Insert a new cell for each object. | |
builder.insertCell(); | |
switch (item.getClass().getName()) | |
{ | |
case "DateTime": | |
// Define a custom format for dates and times. | |
Date dateTime = (Date) item; | |
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM d, yyyy"); | |
builder.write(simpleDateFormat.format(dateTime)); | |
break; | |
default: | |
// By default any other item will be inserted as text. | |
builder.write(item.toString()); | |
break; | |
} | |
} | |
// After we insert all the data from the current record, we can end the table row. | |
builder.endRow(); | |
} | |
// We have finished inserting all the data from the DataTable, we can end the table. | |
builder.endTable(); | |
return table; | |
} |
Phương pháp này sau đó có thể được gọi dễ dàng bằng cách sử dụng DocumentBuilder của bạn và dữ liệu.
Mã ví dụ sau cho thấy cách nhập dữ liệu từ một DataTable
và chèn nó vào bảng mới trong tài liệu:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(); | |
// We can position where we want the table to be inserted and specify any extra formatting to the table. | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// We want to rotate the page landscape as we expect a wide table. | |
doc.getFirstSection().getPageSetup().setOrientation(Orientation.LANDSCAPE); | |
DataSet ds = new DataSet(); | |
ds.readXml(getMyDir() + "List of people.xml"); | |
// Retrieve the data from our data source, which is stored as a DataTable. | |
DataTable dataTable = ds.getTables().get(0); | |
// Build a table in the document from the data contained in the DataTable. | |
Table table = importTableFromDataTable(builder, dataTable, true); | |
// We can apply a table style as a very quick way to apply formatting to the entire table. | |
table.setStyleIdentifier(StyleIdentifier.MEDIUM_LIST_2_ACCENT_1); | |
table.setStyleOptions(TableStyleOptions.FIRST_ROW | TableStyleOptions.ROW_BANDS | TableStyleOptions.LAST_COLUMN); | |
// For our table, we want to remove the heading for the image column. | |
table.getFirstRow().getLastCell().removeAllChildren(); | |
doc.save(getArtifactsDir() + "WorkingWithTables.BuildTableFromDataTable.docx"); |
Bàn trong hình dưới được tạo ra bằng cách chạy đoạn mã trên.