IRONSOFTWAREHOME
開發者更新

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

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: 2026年4月21日

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

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

建立DataTable

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

using System.Data;

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

DataTable dt = new DataTable();

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

DataTable dt = new DataTable("Employees");

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

您可以像資料表中的Id列這樣新增多個列。

新增資料列

定義完列之後,您可以開始向DataTable新增行。 要新增一行,您需要建立一個新的DataRow類實例,並用所需的資料填充其欄位。

以下是一個如何向DataTable新增新行的範例:

DataRow newRow = dt.NewRow();

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

dt.Rows.Add(newRow);

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

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

存取資料

您可以通過遍歷其DataTable中的資料。 以下是在控制台中顯示DataTable內容的範例:

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

修改資料

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

var primaryKey = 1;
DataRow employeeRow = dt.Rows.Find(primaryKey); // Find the row with the specified primary key
if (employeeRow != null)
{
    employeeRow["Age"] = 35;
}

刪除行

您可以通過對DataRow物件呼叫Delete方法從DataTable中刪除一行。

DataRow employeeRow = dt.Rows.Find(1);
if (employeeRow != null)
{
    employeeRow.Delete();
    dt.AcceptChanges(); // Commit the deletion
}

請注意,對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"]);
}

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"]);
}

使用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");
    }
}

在本部分中,我們將學習如何使用IronPDF將DataTable匯出到PDF文件。

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

PM > Install-Package IronPdf

安裝套件後,您可以開始在程式碼中導入所需的命名空間:

using IronPdf;
using System.IO;

接下來,建立一個輔助方法,將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();
}

現在,您可以使用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);
}

DataTable並保存到PDF文件中。

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

string pdfOutputPath = "Employees.pdf";
ExportDataTableToPdf(dt, pdfOutputPath);

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

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

結論

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

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

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.

...
Read More

Related Articles

Key in blue circle

立即免費取得 30 天試用金鑰

bullet_checked無需信用卡或建立帳號
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費現場演示
Booking Badge related to IronPDF Product Demo

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立