跳至頁尾內容
開發者更新

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

歡迎參加這個關於C# DataTables的教程。 一個DataTable是由.NET框架提供的強大的資料結構,允許您以表格格式儲存、操作和查詢資料。 在這個教程中,我們將探討C#中DataTables的基礎,包括建立和修改DataView進行篩選和排序。

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

建立DataTable

要在C#中建立System.Data命名空間。 這個命名空間包含各種與資料操作相關的類和方法,其中包括DataTable類。

using System.Data;
using System.Data;
Imports System.Data
$vbLabelText   $csharpLabel

接下來,您可以建立DataTable類的實例。 最簡單的方法是使用預設構造函式,像這樣:

DataTable dt = new DataTable();
DataTable dt = new DataTable();
Dim dt As New DataTable()
$vbLabelText   $csharpLabel

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

DataTable dt = new DataTable("Employees");
DataTable dt = new DataTable("Employees");
Dim dt As New DataTable("Employees")
$vbLabelText   $csharpLabel

DataTable方法

新增列

一旦建立了DataTable,您就可以開始向其中新增列。 要新增一個列,您首先需要建立DataType

以下是一個如何向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)
$vbLabelText   $csharpLabel

您可以像資料表中的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)
$vbLabelText   $csharpLabel

您也可以在迴圈中使用相同的方法一次新增多個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
$vbLabelText   $csharpLabel

在上面的程式碼中,我們新增了三個資料行。

存取資料

您可以通過遍歷其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
$vbLabelText   $csharpLabel

修改資料

您可以通過更新其DataTable中的資料。 這裡有一個如何更新特定員工年齡的例子:

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

刪除行

您可以通過對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
$vbLabelText   $csharpLabel

請注意,對Delete只會將該行標記為刪除。 您需要對AcceptChanges方法以永久移除被刪除的行。

管理多個表

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

使用LINQ查詢資料

LINQ(語言整合查詢)是C#中的一個強大功能,允許您從各種資料來源(包括DataTable物件)查詢資料。 要在DataTables中使用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
$vbLabelText   $csharpLabel

DataView:排序和篩選

DataTable的排序或篩選視圖。 當您需要在像DataGridView這樣的UI控制元件中顯示資料時,這尤其有用。 我們還可以進行資料繫結,以便從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
$vbLabelText   $csharpLabel

使用IronPDF將DataTable匯出到PDF

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

using IronPdf;

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

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

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

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

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

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

        // 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()

		' 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")

		' 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")

		' 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
$vbLabelText   $csharpLabel

在本部分中,我們將學習如何使用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
$vbLabelText   $csharpLabel

接下來,建立一個輔助方法,將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
$vbLabelText   $csharpLabel

現在,您可以使用HtmlToPdf class由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
$vbLabelText   $csharpLabel

DataTable並保存到PDF文件中。

最後,使用適當的參數調用DataTable

string pdfOutputPath = "Employees.pdf";
ExportDataTableToPdf(dt, pdfOutputPath);
string pdfOutputPath = "Employees.pdf";
ExportDataTableToPdf(dt, pdfOutputPath);
Dim pdfOutputPath As String = "Employees.pdf"
ExportDataTableToPdf(dt, pdfOutputPath)
$vbLabelText   $csharpLabel

這將建立一個名為"Employees.pdf"的PDF文件,包含您的DataTable的內容,以表格格式展示。

C# DataTable(其對開發者的運作方式教程) - 圖1

結論

在這個教程中,您已經學會了C#中DataTables的基礎知識,以及如何使用IronPDF程式庫將DataTable匯出到PDF文件。 通過包含主鍵列、資料集變數和DataView進行篩選和排序,您將擁有更大的資料控制和靈活性。 現在,您應該對DataTables以及如何將IronPDF與DataTables結合使用,以在您的C#應用程式中建立專業外觀的PDF報告有良好的理解。

IronPDF提供其功能的免費試用,允許您在購買前探索其能力。

常見問題

什麼是C#中的DataTable?

DataTable 是 .NET framework 中一個多功能的資料結構,允許開發者以表格格式儲存、操作和查詢資料,使其在應用程式中處理結構化資料時至關重要。

我如何在C#中將DataTable轉換為PDF文件?

若要在C#中將DataTable轉換為PDF文件,首先將DataTable轉換為HTML表格。使用IronPDF的HtmlToPdf類將該HTML渲染為PDF文件並保存生成的檔案。

您如何在C#中建立一個DataTable?

在C#中建立DataTable涉及到匯入System.Data命名空間,並使用其構造函式實例化DataTable類,可選擇為DataTable提供一個特定名稱。

新增列到DataTable的步驟是什麼?

新增列到DataTable中,需建立DataColumn類的實例,配置如ColumnName和DataType等屬性,並將其新增到DataTable的Columns集合中。

我如何將DataTable中的資料匯出到PDF以用于報告目的?

您可以通過將DataTable轉換為HTML表格式,然後使用IronPDF將此HTML渲染為PDF文件,建立出專業級的報告。

您如何在C#中向DataTable新增行?

在C#中向DataTable新增行,需要建立新的DataRow實例,填充資料,並將其新增到DataTable的Rows集合中。此過程可通過迴圈對多行重複進行。

什麼是LINQ以及如何在DataTables中使用它?

LINQ(Language Integrated Query)是在C#中的一種強大的查询工具,它使能過濾、排序和操作來自各種來源的資料,包括DataTables,以簡化資料操作。

我如何使用DataView來過濾和排序DataTable?

DataView提供了一種方便的方法來建立DataTable的過濾或排序視圖。通過設置RowFilter和Sort屬性,您可以控制資料如何顯示,在UI組件中特別有用。

如何安裝將DataTables匯出到PDF所需的程式庫?

若要安裝將DataTables匯出到PDF所需的IronPDF程式庫,使用Visual Studio中的套件管理器主控台並執行命令:Install-Package IronPdf

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話