2009-03-27 29 views
5

Có được xác định trước hoặc phương pháp "dễ dàng" viết một DataTable vào một tập tin văn bản hoặc TextBox Control (Với phông chữ monospace) như DataTable.Print():In một DataTable để textbox/textfile trong .NET

 
Column1| Column2| 
--------|--------| 
     v1|  v2| 
     v3|  v4| 
     v5|  v6| 

Sửa

Dưới đây là một phiên bản ban đầu (vb.net) - trong trường hợp có ai quan tâm hoặc muốn xây dựng của riêng mình:

Public Function BuildTable(ByVal dt As DataTable) As String 

    Dim result As New StringBuilder 
    Dim widths As New List(Of Integer) 
    Const ColumnSeparator As Char = "|"c 
    Const HeadingUnderline As Char = "-"c 

    ' determine width of each column based on widest of either column heading or values in that column 
    For Each col As DataColumn In dt.Columns 
     Dim colWidth As Integer = Integer.MinValue 
     For Each row As DataRow In dt.Rows 
      Dim len As Integer = row(col.ColumnName).ToString.Length 
      If len > colWidth Then 
       colWidth = len 
      End If 
     Next 
     widths.Add(CInt(IIf(colWidth < col.ColumnName.Length, col.ColumnName.Length + 1, colWidth + 1))) 
    Next 

    ' write column headers 
    For Each col As DataColumn In dt.Columns 
     result.Append(col.ColumnName.PadLeft(widths(col.Ordinal))) 
     result.Append(ColumnSeparator) 
    Next 
    result.AppendLine() 

    ' write heading underline 
    For Each col As DataColumn In dt.Columns 
     Dim horizontal As String = New String(HeadingUnderline, widths(col.Ordinal)) 
     result.Append(horizontal.PadLeft(widths(col.Ordinal))) 
     result.Append(ColumnSeparator) 
    Next 
    result.AppendLine() 

    ' write each row 
    For Each row As DataRow In dt.Rows 
     For Each col As DataColumn In dt.Columns 
      result.Append(row(col.ColumnName).ToString.PadLeft(widths(col.Ordinal))) 
      result.Append(ColumnSeparator) 
     Next 
     result.AppendLine() 
    Next 

    Return result.ToString() 

End Function 

Trả lời

1

Không, có isn 't. Bạn sẽ phải tự định dạng hoặc tìm một thư viện của bên thứ ba sẽ tự làm điều này.

+0

Có, cảm ơn bạn, tôi sẽ bận rộn bằng văn bản của riêng tôi. – user79755

3

Bạn có thể sử dụng một DataTableReader:

public static string PrintTable(this DataTable dt) 
{ 
    DataTableReader dtReader = dt.CreateDataReader(); 
    StringBuilder result = new StringBuilder(); 
    while (dtReader.Read()) 
    { 
     for (int i = 0; i < dtReader.FieldCount; i++) 
     { 
      result.AppendFormat("{0} = {1}", 
       dtReader.GetName(i).Trim(), 
       dtReader.GetValue(i).ToString().Trim()); 
     } 
     result.AppendLine(); 
    } 
    dtReader.Close(); 
    return result.ToString(); 
} 
+0

Cảm ơn bạn đã lấy mẫu mã. – user79755

4

tôi khuyên bạn nên kiểm tra bài viết của tôi DataTable Formatter.
Lớp DataTableFormatter của tôi chứa các phương thức định dạng DataTables dưới dạng bảng dựa trên ký tự (yêu cầu của bạn), bảng HTML hoặc bảng tài liệu luồng.

Bạn có thể tải xuống dự án chứa lớp học từ trang web của mình, nhưng để thuận tiện, tôi sẽ đăng mã ở đây.

/// <summary> 
/// Gets a string representation of the <see cref="System.Data.DataTable" />. 
/// </summary> 
/// <remarks>The string representation should be displayed with a monospaced font.</remarks> 
public static string GetStringRepresentation(DataTable dataTable) 
{ 
    if (dataTable == null) 
     throw new ArgumentNullException("'dataTable' cannot be null."); 

    StringWriter representationWriter = new StringWriter(); 

    // First, set the width of every column to the length of its largest element. 
    int[] columnWidths = new int[dataTable.Columns.Count]; 
    for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++) 
    { 
     int headerWidth = dataTable.Columns[columnIndex].ColumnName.Length; 
     int longestElementWidth = dataTable.AsEnumerable() 
      .Select((row) => row[columnIndex].ToString().Length) 
      .Max(); 
     columnWidths[columnIndex] = Math.Max(headerWidth, longestElementWidth); 
    } 

    // Next, write the table 
    // Write a horizontal line. 
    representationWriter.Write("+-"); 
    for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++) 
    { 
     for (int i = 0; i < columnWidths[columnIndex]; i++) 
      representationWriter.Write("-"); 
     representationWriter.Write("-+"); 
     if (columnIndex != dataTable.Columns.Count - 1) 
      representationWriter.Write("-"); 
    } 
    representationWriter.WriteLine(" "); 
    // Print the headers 
    representationWriter.Write("| "); 
    for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++) 
    { 
     string header = dataTable.Columns[columnIndex].ColumnName; 
     representationWriter.Write(header); 
     for (int blanks = columnWidths[columnIndex] - header.Length; blanks > 0; blanks--) 
      representationWriter.Write(" "); 
     representationWriter.Write(" | "); 
    } 
    representationWriter.WriteLine(); 
    // Print another horizontal line. 
    representationWriter.Write("+-"); 
    for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++) 
    { 
     for (int i = 0; i < columnWidths[columnIndex]; i++) 
      representationWriter.Write("-"); 
     representationWriter.Write("-+"); 
     if (columnIndex != dataTable.Columns.Count - 1) 
      representationWriter.Write("-"); 
    } 
    representationWriter.WriteLine(" "); 

    // Print the contents of the table. 
    for (int row = 0; row < dataTable.Rows.Count; row++) 
    { 
     representationWriter.Write("| "); 
     for (int column = 0; column < dataTable.Columns.Count; column++) 
     { 
      representationWriter.Write(dataTable.Rows[row][column]); 
      for (int blanks = columnWidths[column] - dataTable.Rows[row][column].ToString().Length; 
       blanks > 0; blanks--) 
       representationWriter.Write(" "); 
      representationWriter.Write(" | "); 
     } 
     representationWriter.WriteLine(); 
    } 

    // Print a final horizontal line. 
    representationWriter.Write("+-"); 
    for (int column = 0; column < dataTable.Columns.Count; column++) 
    { 
     for (int i = 0; i < columnWidths[column]; i++) 
      representationWriter.Write("-"); 
     representationWriter.Write("-+"); 
     if (column != dataTable.Columns.Count - 1) 
      representationWriter.Write("-"); 
    } 
    representationWriter.WriteLine(" "); 

    return representationWriter.ToString(); 
} 

Phương pháp GetStringRepresentation (DataTable) cho kết quả như thế này

 

    +------------------+----------------+-------------------+ 
    | Item    | Units in Stock | Unit Price  | 
    +------------------+----------------+-------------------+ 
    | Drilling machine | 1000   | $1,000,000  | 
    | Backpack   | 320   | $24    | 
    | Chocolate bar | 100000   | $2.00000000000000 | 
    +------------------+----------------+-------------------+ 

tôi nên thừa nhận rằng phong cách bảng này là lừa từ dòng lệnh MySQL client.

+0

+1 Chỉ là những gì tôi đang tìm kiếm. – blak3r

+0

Cảm ơn rất nhiều. Chỉ là những gì tôi muốn. – captonssj

Các vấn đề liên quan