DataTable 에서 테이블 작성
애플리케이션이 데이터베이스에서 데이터를 가져와 DataTable 형식으로 저장하는 경우가 많습니다. 이 데이터를 문서에 새 표로 쉽게 삽입하고 전체 표에 서식을 빠르게 적용할 수 있습니다.
Aspose.Words를 사용하면 데이터베이스에서 데이터를 쉽게 검색하여 테이블로 저장할 수 있습니다
- Document에 새 DocumentBuilder 개체를 만듭니다.
- DocumentBuilder를 사용하여 새 테이블을 시작합니다.
- DataTable의 각 열 이름을 헤더 행으로 삽입하려면 각 데이터 열을 반복하고 테이블의 행에 열 이름을 씁니다.
- DataTable의 각 DataRow를 반복합니다
- DataRow의 각 객체를 반복합니다.
- DocumentBuilder를 사용하여 문서에 개체를 삽입합니다. 사용되는 방법은 삽입되는 개체의 유형에 따라 다릅니다. 예를 들어 텍스트의 경우 DocumentBuilder.Writeln, 이미지를 나타내는 바이트 배열의 경우 DocumentBuilder.InsertImage이 있습니다.
- DataRow 처리가 끝나면 DocumentBuilder.EndRow을 사용하여 DocumentBuilder에서 생성되는 행도 종료됩니다.
- DataTable의 모든 행이 처리되면 DocumentBuilder.EndTable를 호출하여 테이블을 완료합니다.
- 마지막으로 Table.StyleIdentifier와 같은 적절한 테이블 속성 중 하나를 사용하여 원하는 테이블 스타일을 설정하여 전체 테이블에 서식을 자동으로 적용할 수 있습니다.
ImportTableFromDataTable 메소드는 DocumentBuilder 객체, 데이터가 포함된 DataTable 및 DataTable의 열 제목이 테이블 상단에 포함되는지 여부를 지정하는 플래그를 허용합니다. 이 메소드는 빌더의 현재 위치와 형식을 사용하여 이러한 매개변수로부터 테이블을 작성합니다. DataTable
에서 데이터를 가져와 DocumentBuilder를 사용하여 새 테이블에 삽입하는 방법을 제공합니다.
이 예에서는 DataTable의 다음 데이터가 사용되었습니다
다음 코드 예제는 Aspose.Words에서 위의 알고리즘을 실행하는 방법을 보여줍니다
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.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, | |
bool 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. | |
bool boldValue = builder.Font.Bold; | |
ParagraphAlignment paragraphAlignmentValue = builder.ParagraphFormat.Alignment; | |
// Format the heading row with the appropriate properties. | |
builder.Font.Bold = true; | |
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; | |
// Create a new row and insert the name of each column into the first row of the table. | |
foreach (DataColumn column in dataTable.Columns) | |
{ | |
builder.InsertCell(); | |
builder.Writeln(column.ColumnName); | |
} | |
builder.EndRow(); | |
// Restore the original formatting. | |
builder.Font.Bold = boldValue; | |
builder.ParagraphFormat.Alignment = paragraphAlignmentValue; | |
} | |
foreach (DataRow dataRow in dataTable.Rows) | |
{ | |
foreach (object item in dataRow.ItemArray) | |
{ | |
// Insert a new cell for each object. | |
builder.InsertCell(); | |
switch (item.GetType().Name) | |
{ | |
case "DateTime": | |
// Define a custom format for dates and times. | |
DateTime dateTime = (DateTime) item; | |
builder.Write(dateTime.ToString("MMMM d, yyyy")); | |
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-.NET.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.FirstSection.PageSetup.Orientation = Orientation.Landscape; | |
DataSet ds = new DataSet(); | |
ds.ReadXml(MyDir + "List of people.xml"); | |
// Retrieve the data from our data source, which is stored as a DataTable. | |
DataTable dataTable = ds.Tables[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.StyleIdentifier = StyleIdentifier.MediumList2Accent1; | |
table.StyleOptions = TableStyleOptions.FirstRow | TableStyleOptions.RowBands | TableStyleOptions.LastColumn; | |
// For our table, we want to remove the heading for the image column. | |
table.FirstRow.LastCell.RemoveAllChildren(); | |
doc.Save(ArtifactsDir + "WorkingWithTables.BuildTableFromDataTable.docx"); |