Zbuduj tabelę z pliku DataTable

Contents
[ ]

Często Twoja aplikacja będzie pobierać dane z bazy danych i przechowywać je w formie DataTable. Możesz łatwo wstawić te dane do swojego dokumentu jako nową tabelę i szybko zastosować formatowanie do całej tabeli.

Używając Aspose.Words, możesz łatwo pobrać dane z bazy danych i zapisać je w postaci tabeli:

  1. Utwórz nowy obiekt DocumentBuilder na swoim Document.
  2. Rozpocznij nową tabelę za pomocą DocumentBuilder.
  3. Jeśli chcemy wstawić nazwy każdej kolumny z naszego DataTable jako wiersz nagłówka, wykonaj iterację po każdej kolumnie danych i wpisz nazwy kolumn w wierszu tabeli.
  4. Iteruj po każdym DataRow w DataTable:
    1. Wykonaj iterację po każdym obiekcie w DataRow.
    2. Wstaw obiekt do dokumentu za pomocą DocumentBuilder. Zastosowana metoda zależy od typu wstawianego obiektu, np. DocumentBuilder.Writeln dla tekstu i DocumentBuilder.InsertImage dla tablicy bajtów reprezentującej obraz.
    3. Na koniec przetwarzania DataRow zakończ także wiersz tworzony przez DocumentBuilder, używając DocumentBuilder.EndRow.
  5. Po przetworzeniu wszystkich wierszy z DataTable zakończ tabelę wywołując DocumentBuilder.EndTable.
  6. Na koniec możemy ustawić żądany styl tabeli, korzystając z jednej z odpowiednich właściwości tabeli, takich jak Table.StyleIdentifier, aby automatycznie zastosować formatowanie do całej tabeli.

Metoda ImportTableFromDataTable akceptuje obiekt DocumentBuilder, plik DataTable zawierający dane oraz flagę określającą, czy nagłówek kolumny z formatu DataTable znajduje się na górze tabeli. Ta metoda tworzy tabelę na podstawie tych parametrów, korzystając z bieżącej pozycji i formatowania konstruktora. Zapewnia metodę importowania danych z formatu DataTable i wstawiania ich do nowej tabeli przy użyciu narzędzia DocumentBuilder.

W tym przykładzie wykorzystano następujące dane z naszego DataTable:

how-to-build-a-table-from-a-datatable-aspose-words-net

Poniższy przykład kodu pokazuje, jak wykonać powyższy algorytm w 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;
}

Metodę można następnie łatwo wywołać, korzystając z pliku DocumentBuilder i danych.

Poniższy przykład kodu pokazuje, jak zaimportować dane z DataTable i wstawić je do nowej tabeli w dokumencie:

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