DataTable에서 테이블 빌드

Contents
[ ]

종종 응용 프로그램은 데이터베이스에서 데이터를 가져와DataTable형태로 저장합니다. 이 데이터를 문서에 새 테이블로 쉽게 삽입하고 전체 테이블에 서식을 빠르게 적용 할 수 있습니다.

Aspose.Words을 사용하면 데이터베이스에서 데이터를 쉽게 검색하고 테이블로 저장할 수 있습니다:

  1. Document에 새DocumentBuilder개체를 만듭니다.
  2. DocumentBuilder을 사용하여 새 테이블을 시작합니다.
  3. DataTable의 각 열의 이름을 머리글 행으로 삽입하려면 각 데이터 열을 반복하고 열 이름을 테이블의 행에 씁니다.
  4. DataTable의 각DataRow를 반복합니다:
    1. DataRow의 각 개체를 반복합니다.
    2. DocumentBuilder를 사용하여 개체를 문서에 삽입합니다. 사용되는 방법은 삽입되는 객체의 유형에 따라 달라집니다.예를 들어 텍스트의DocumentBuilder.writeln()와 이미지를 나타내는 바이트 배열의DocumentBuilder.insertImage()입니다.
    3. 데이터 행의 처리가 끝나면DocumentBuilder.endRow()을 사용하여DocumentBuilder에 의해 생성되는 행도 끝납니다.
  5. DataTable의 모든 행이 처리되면DocumentBuilder.endTable()을 호출하여 테이블을 마칩니다.
  6. 마지막으로Table.getStyleIdentifier()과 같은 적절한 테이블 속성 중 하나를 사용하여 원하는 테이블 스타일을 설정하여 전체 테이블에 서식을 자동으로 적용 할 수 있습니다. 이 예제에서는DataTable의 다음 데이터를 사용합니다:

build-a-table-from-a-datatable-aspose-words-java-1

다음 코드 예제에서는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;
}

그런 다음DocumentBuilder및 데이터를 사용하여 메서드를 쉽게 호출 할 수 있습니다.

다음 코드 예제에서는DataTable에서 데이터를 가져와 문서의 새 테이블에 삽입하는 방법을 보여 줍니다:

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

아래 그림에 표시된 표는 위의 코드를 실행하여 생성됩니다.

build-a-table-from-a-datatable-aspose-words-java-2