.NET幫助 C# DataTable(開發者的工作原理教程) Curtis Chau 更新日期:6月 22, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 歡迎來到這個關於C#資料表的教程。 DataTable是一個由.NET框架提供的強大數據結構,允許您以表格格式存儲、操作和查詢數據。 在本教程中,我們將探討C#中DataTable的基本概念,包括創建和修改DataTable、添加列和行、查詢數據以及使用DataView進行篩選和排序。 在本教程結束時,您將對如何在C#應用程式中使用DataTable有一個良好的理解。 讓我們開始吧! 創建DataTable 若要在C#中創建DataTable,首先需要導入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後,您可以開始向其中添加列。 若要添加一列,首先需要創建DataColumn類的實例並設置其屬性,如ColumnName和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的Rows和Columns集合來訪問存儲在其中的數據。 以下是如何在控制台中顯示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 修改數據 可以通過更新DataRow對象中的值來修改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 請記住,對DataRow調用Delete僅僅是標記該行為刪除。 您需要在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 $vbLabelText $csharpLabel DataView:排序和篩選 DataView是由System.Data命名空間提供的另一個有用類,允許您創建DataTable的排序或篩選視圖。 這在需要在UI控制項中顯示數據時特別有用,例如DataGridView。 我們還可以數據綁定,以便從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 $vbLabelText $csharpLabel 使用IronPDF導出DataTable到PDF IronPDF is a powerful 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 現在,您可以使用IronPDF提供的HtmlToPdf類渲染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 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) $vbLabelText $csharpLabel 這將創建一個名為"Employees.pdf"的PDF文件,其中含有您的DataTable的表格格式內容。 結論 通過這個教程,您學到了C#中DataTable的基本知識以及如何使用IronPDF庫將DataTable導出為PDF文檔。 通過合併主鍵列、數據集合變量和DataView進行篩選和排序,您將對數據擁有更大的控制和靈活性。 現在,您應該對DataTable有一個很好的理解,並知道如何將IronPDF與DataTable結合使用,以便在C#應用程式中創建專業外觀的PDF報告。 IronPDF提供其功能的免費試用版,允許您在購買前探索其能力。 常見問題解答 什麼是 C# 中的 DataTable? DataTable 是 .NET 框架中一種多功能數據結構,允許開發者以表格式存儲、操作和查詢數據,對於應用程式中處理結構化數據至關重要。 如何在 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(語言集成查詢)是 C# 中強大的查詢工具,可對來自包括 DataTables 在內的各種來源的數據進行篩選、排序和操作,以簡化數據操作。 如何使用 DataView 過濾和排序 DataTable? DataView 提供了一種方便的方法來創建 DataTable 的篩選或排序視圖。通過設置 RowFilter 和 Sort 屬性,您可以控制數據的顯示方式,這在 UI 組件中尤為有用。 如何安裝導出 DataTables 為 PDF 的必要庫? 要安裝導出 DataTables 為 PDF 的 IronPDF 庫,請使用 Visual Studio 中的套件管理控制台並執行命令:Install-Package IronPdf。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 安裝 NuGet Powershell(開發者的工作原理教程)如何在C#中使用.NET Fiddle