.NET 幫助

C# DataTable(開發人員教程的工作原理)

發佈 2023年5月8日
分享:

歡迎閱讀這篇關於C# DataTables的教程。DataTable 是由 .NET 框架提供的一個強大的數據結構,它允許您以表格格式存儲、操作和查詢數據。在本教程中,我們將探討 C# 中 DataTables 的基礎知識,包括創建和修改DataTables,添加列和行,查詢數據,並使用DataView進行過濾和排序。

在本教程結束時,您將對如何在您的C#應用程序中使用DataTables有一個良好的理解。讓我們開始吧。!

創建 DataTable

要在 C# 中創建 DataTable,首先需要導入 System.Data 命名空間。這個命名空間包含了與數據操作相關的各種類和方法,包括 DataTable 類。

 using System.Data;
 using System.Data;
Imports System.Data
VB   C#

接下來,你可以創建一個 DataTable 類的實例。最簡單的方法是使用默認構造函數,如下所示:

DataTable dt = new DataTable();
DataTable dt = new DataTable();
Dim dt As New DataTable()
VB   C#

您還可以通過向構造函數傳遞一個字串參數來創建具有特定名稱的 DataTable

DataTable dt = new DataTable("Employees");
DataTable dt = new DataTable("Employees");
Dim dt As New DataTable("Employees")
VB   C#

資料表方法

添加列

一旦您創建了 DataTable,就可以開始向其中添加列。要添加列,首先需要創建 DataColumn 類的實例,並設置其屬性,例如 ColumnNameDataType

以下是如何向 DataTable 添加三列的示例:

DataColumn idColumn = new DataColumn("Id", typeof(int));
DataColumn nameColumn = new DataColumn("Name", typeof(string));
DataColumn ageColumn = new DataColumn("Age", typeof(int));

dt.Columns.Add(idColumn);
dt.Columns.Add(nameColumn);
dt.Columns.Add(ageColumn);
DataColumn idColumn = new DataColumn("Id", typeof(int));
DataColumn nameColumn = new DataColumn("Name", typeof(string));
DataColumn ageColumn = new DataColumn("Age", typeof(int));

dt.Columns.Add(idColumn);
dt.Columns.Add(nameColumn);
dt.Columns.Add(ageColumn);
Dim idColumn As New DataColumn("Id", GetType(Integer))
Dim nameColumn As New DataColumn("Name", GetType(String))
Dim ageColumn As New DataColumn("Age", GetType(Integer))

dt.Columns.Add(idColumn)
dt.Columns.Add(nameColumn)
dt.Columns.Add(ageColumn)
VB   C#

您可以在數據表中添加多個類似 Id 欄的欄位。

添加資料列

定義欄位後,您可以開始向 DataTable 添加資料列。要添加一個資料列,您需要創建一個新的 DataRow 實例並用所需的數據填充它的字段。

以下是如何向 DataTable 添加新資料列的一個例子:

DataRow newRow = dt.NewRow();

newRow ["Id"] = 1;
newRow ["Name"] = "John Doe";
newRow ["Age"] = 30;

dt.Rows.Add(newRow);
DataRow newRow = dt.NewRow();

newRow ["Id"] = 1;
newRow ["Name"] = "John Doe";
newRow ["Age"] = 30;

dt.Rows.Add(newRow);
Dim newRow As DataRow = dt.NewRow()

newRow ("Id") = 1
newRow ("Name") = "John Doe"
newRow ("Age") = 30

dt.Rows.Add(newRow)
VB   C#

您也可以使用相同的方法在迴圈中一次新增多個 DataTable 列。

for (int i = 1; i <= 3; i++)
{
    DataRow row = dt.NewRow();
    row ["Id"] = i;
    row ["Name"] = "Employee " + i;
    row ["Age"] = 20 + i;
    dt.Rows.Add(row);
}
for (int i = 1; i <= 3; i++)
{
    DataRow row = dt.NewRow();
    row ["Id"] = i;
    row ["Name"] = "Employee " + i;
    row ["Age"] = 20 + i;
    dt.Rows.Add(row);
}
For i As Integer = 1 To 3
	Dim row As DataRow = dt.NewRow()
	row ("Id") = i
	row ("Name") = "Employee " & i
	row ("Age") = 20 + i
	dt.Rows.Add(row)
Next i
VB   C#

在上述程式碼中,我們新增了三筆資料列。

訪問數據

您可以通過遍歷 RowsColumns 集合來訪問儲存在 DataTable 中的數據。以下是一個在控制台中顯示 DataTable 內容的範例:

foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn col in dt.Columns)
    {
        Console.Write(row [col] + "\t");
    }
    Console.WriteLine();
}
foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn col in dt.Columns)
    {
        Console.Write(row [col] + "\t");
    }
    Console.WriteLine();
}
Imports Microsoft.VisualBasic

For Each row As DataRow In dt.Rows
	For Each col As DataColumn In dt.Columns
		Console.Write(row (col) & vbTab)
	Next col
	Console.WriteLine()
Next row
VB   C#

修改資料

您可以透過更新 DataRow 物件中的值來修改 DataTable 中的資料。以下是一個更新特定員工年齡的例子:

DataRow employeeRow = dt.Rows.Find(1); // Find the row with the specified primary key
if (employeeRow != null)
{
    employeeRow ["Age"] = 35;
}
DataRow employeeRow = dt.Rows.Find(1); // Find the row with the specified primary key
if (employeeRow != null)
{
    employeeRow ["Age"] = 35;
}
Dim employeeRow As DataRow = dt.Rows.Find(1) ' Find the row with the specified primary key
If employeeRow IsNot Nothing Then
	employeeRow ("Age") = 35
End If
VB   C#

刪除列

您可以通過對 DataRow 物件調用 Delete 方法來從 DataTable 刪除一列:

DataRow employeeRow = dt.Rows.Find(1);
if (employeeRow != null)
{
    employeeRow.Delete();
    dt.AcceptChanges(); // Commit the deletion
}
DataRow employeeRow = dt.Rows.Find(1);
if (employeeRow != null)
{
    employeeRow.Delete();
    dt.AcceptChanges(); // Commit the deletion
}
Dim employeeRow As DataRow = dt.Rows.Find(1)
If employeeRow IsNot Nothing Then
	employeeRow.Delete()
	dt.AcceptChanges() ' Commit the deletion
End If
VB   C#

請注意,調用 DeleteDataRow 上只會將該行標記為刪除。你需要在 DataTable 上調用 AcceptChanges 方法來永久刪除已刪除的行。

管理多個表格

在某些情況下,您可能需要同時處理多個資料表。您可以建立一個資料集變數,以儲存多個 DataTable 物件並管理它們之間的關係。

使用 LINQ 查詢資料

LINQ (語言集成查詢) 在C#中是一個強大的功能,可讓您從各種數據源(包括DataTable對象)中查詢數據。要在 DataTable 中使用 LINQ,您需要匯入System.Linq命名空間。以下是如何使用 LINQ 篩選年齡大於 25 歲的員工的示例:

using System.Linq;

var filteredRows = dt.AsEnumerable().Where(row => row.Field<int>("Age") > 25);

foreach (DataRow row in filteredRows)
{
    Console.WriteLine(row ["Name"]);
}
using System.Linq;

var filteredRows = dt.AsEnumerable().Where(row => row.Field<int>("Age") > 25);

foreach (DataRow row in filteredRows)
{
    Console.WriteLine(row ["Name"]);
}
Imports System.Linq

Private filteredRows = dt.AsEnumerable().Where(Function(row) row.Field(Of Integer)("Age") > 25)

For Each row As DataRow In filteredRows
	Console.WriteLine(row ("Name"))
Next row
VB   C#

DataView:排序和篩選

DataViewSystem.Data 命名空間中提供的另一個有用的類別,它允許你創建 DataTable 的排序或篩選視圖。當你需要在像 DataGridView 這樣的 UI 控件中顯示數據時,這特別有用。我們也可以進行數據繫結,將 DataTable 中的數據添加到 DataGridView 控件中。

以下是如何創建一個 DataView 來根據員工的年齡進行篩選和排序的示例:

DataView view = new DataView(dt);

// Filter employees older than 25
view.RowFilter = "Age > 25";

// Sort by age in descending order
view.Sort = "Age DESC";

// Display the filtered and sorted data
foreach (DataRowView rowView in view)
{
    DataRow row = rowView.Row;
    Console.WriteLine(row ["Name"]);
}
DataView view = new DataView(dt);

// Filter employees older than 25
view.RowFilter = "Age > 25";

// Sort by age in descending order
view.Sort = "Age DESC";

// Display the filtered and sorted data
foreach (DataRowView rowView in view)
{
    DataRow row = rowView.Row;
    Console.WriteLine(row ["Name"]);
}
Dim view As New DataView(dt)

' Filter employees older than 25
view.RowFilter = "Age > 25"

' Sort by age in descending order
view.Sort = "Age DESC"

' Display the filtered and sorted data
For Each rowView As DataRowView In view
	Dim row As DataRow = rowView.Row
	Console.WriteLine(row ("Name"))
Next rowView
VB   C#

使用 IronPDF 將 DataTable 導出為 PDF

IronPDF 是一個強大的 HTML轉PDF 轉換器,配備用戶友好的PDF操作功能,使開發者能夠在 .NET 應用程序中創建、閱讀和編輯PDF文件。

using IronPdf;

class Program
{
    static void Main(string [] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string [] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

在本節中,我們將學習如何使用 IronPDF 將 DataTable 導出為 PDF 文件。

首先,你需要安裝 IronPDF NuGet 套件。打開 Visual Studio 的套件管理器控制台,並運行以下命令:

Install-Package IronPdf

一旦安裝封包後,您可以在代碼中開始匯入必要的命名空間:

using IronPdf;
using System.IO;
using IronPdf;
using System.IO;
Imports IronPdf
Imports System.IO
VB   C#

接下來,建立一個輔助方法,將DataTable轉換為HTML表格,因為IronPDF使用HTML來渲染PDF文件中的內容:

public static string ConvertDataTableToHtml(DataTable dt)
{
    StringBuilder htmlBuilder = new StringBuilder();

    htmlBuilder.AppendLine("<table border='1' cellpadding='5' cellspacing='0'>");
    htmlBuilder.AppendLine("<tr>");

    // Add column headers
    foreach (DataColumn col in dt.Columns)
    {
        htmlBuilder.AppendFormat("<th>{0}</th>", col.ColumnName);
    }

    htmlBuilder.AppendLine("</tr>");

    // Add rows
    foreach (DataRow row in dt.Rows)
    {
        htmlBuilder.AppendLine("<tr>");

        foreach (DataColumn col in dt.Columns)
        {
            htmlBuilder.AppendFormat("<td>{0}</td>", row [col]);
        }

        htmlBuilder.AppendLine("</tr>");
    }

    htmlBuilder.AppendLine("</table>");

    return htmlBuilder.ToString();
}
public static string ConvertDataTableToHtml(DataTable dt)
{
    StringBuilder htmlBuilder = new StringBuilder();

    htmlBuilder.AppendLine("<table border='1' cellpadding='5' cellspacing='0'>");
    htmlBuilder.AppendLine("<tr>");

    // Add column headers
    foreach (DataColumn col in dt.Columns)
    {
        htmlBuilder.AppendFormat("<th>{0}</th>", col.ColumnName);
    }

    htmlBuilder.AppendLine("</tr>");

    // Add rows
    foreach (DataRow row in dt.Rows)
    {
        htmlBuilder.AppendLine("<tr>");

        foreach (DataColumn col in dt.Columns)
        {
            htmlBuilder.AppendFormat("<td>{0}</td>", row [col]);
        }

        htmlBuilder.AppendLine("</tr>");
    }

    htmlBuilder.AppendLine("</table>");

    return htmlBuilder.ToString();
}
Public Shared Function ConvertDataTableToHtml(ByVal dt As DataTable) As String
	Dim htmlBuilder As New StringBuilder()

	htmlBuilder.AppendLine("<table border='1' cellpadding='5' cellspacing='0'>")
	htmlBuilder.AppendLine("<tr>")

	' Add column headers
	For Each col As DataColumn In dt.Columns
		htmlBuilder.AppendFormat("<th>{0}</th>", col.ColumnName)
	Next col

	htmlBuilder.AppendLine("</tr>")

	' Add rows
	For Each row As DataRow In dt.Rows
		htmlBuilder.AppendLine("<tr>")

		For Each col As DataColumn In dt.Columns
			htmlBuilder.AppendFormat("<td>{0}</td>", row (col))
		Next col

		htmlBuilder.AppendLine("</tr>")
	Next row

	htmlBuilder.AppendLine("</table>")

	Return htmlBuilder.ToString()
End Function
VB   C#

現在,您可以使用 HtmlToPdf IronPDF 提供的類別,用於渲染 HTML 表格並將其保存為 PDF 文件:

public static void ExportDataTableToPdf(DataTable dt, string outputPath)
{
    // Convert DataTable to HTML
    string htmlTable = ConvertDataTableToHtml(dt);

    // Create a new HTML to PDF renderer
    var renderer = new ChromePdfRenderer();

    // Set global styles for the table
    renderer.RenderingOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
    renderer.RenderingOptions.FirstPageNumber = 1;

    // Render the HTML table as a PDF document
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlTable);

    // Save the PDF file
    pdf.SaveAs(outputPath);
}
public static void ExportDataTableToPdf(DataTable dt, string outputPath)
{
    // Convert DataTable to HTML
    string htmlTable = ConvertDataTableToHtml(dt);

    // Create a new HTML to PDF renderer
    var renderer = new ChromePdfRenderer();

    // Set global styles for the table
    renderer.RenderingOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
    renderer.RenderingOptions.FirstPageNumber = 1;

    // Render the HTML table as a PDF document
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlTable);

    // Save the PDF file
    pdf.SaveAs(outputPath);
}
Public Shared Sub ExportDataTableToPdf(ByVal dt As DataTable, ByVal outputPath As String)
	' Convert DataTable to HTML
	Dim htmlTable As String = ConvertDataTableToHtml(dt)

	' Create a new HTML to PDF renderer
	Dim renderer = New ChromePdfRenderer()

	' Set global styles for the table
	renderer.RenderingOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
	renderer.RenderingOptions.FirstPageNumber = 1

	' Render the HTML table as a PDF document
	Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlTable)

	' Save the PDF file
	pdf.SaveAs(outputPath)
End Sub
VB   C#

ExportDataTableToPdf 方法從 HTML 表格建立 DataTable,並將其儲存到 PDF 檔案中。

最後,使用適當的參數呼叫 ExportDataTableToPdf 方法來匯出您的 DataTable

string pdfOutputPath = "Employees.pdf";
ExportDataTableToPdf(dt, pdfOutputPath);
string pdfOutputPath = "Employees.pdf";
ExportDataTableToPdf(dt, pdfOutputPath);
Dim pdfOutputPath As String = "Employees.pdf"
ExportDataTableToPdf(dt, pdfOutputPath)
VB   C#

這將創建一個名為 "Employees.pdf" 的 PDF 檔案,其中包含以表格式顯示的 DataTable 內容。

C# DataTable (開發人員教程中的工作原理) - 圖 1

結論

在本教程中,您已經學習了在 C# 中使用 DataTables 的基礎知識,以及如何使用 IronPDF 庫將 DataTable 導出為 PDF 文件。通過加入主鍵列、數據集變量和 DataView 進行篩選和排序,您將對數據有更大的控制和靈活性。現在您應該對 DataTables 有了很好的理解,並知道如何在 C# 應用程序中結合使用 IronPDF 和 DataTables 來創建專業的 PDF 報告。

IronPDF 提供了一個 免費試用,讓您在購買前先探索其功能和能力。

< 上一頁
安裝 NuGet Powershell(開發人員教程工作原理)
下一個 >
如何在 C# 中使用 .NET Fiddle

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >