C# DataTable(開發者的工作原理教程)
歡迎來到此 C# DataTables 教學。 A DataTable 是 .NET 框架提供的強大的資料結構,它允許您以表格格式儲存、操作和查詢資料。 在本教程中,我們將探索 C# 中 DataTables 的基礎知識,包括建立和修改 DataTables、新增列和行、查詢資料以及使用 DataView 進行篩選和排序。
在本教程結束時,您將很好地了解如何在 C# 應用程式中使用 DataTables。 讓我們開始吧
建立 DataTable
要在 C# 中建立 DataTable,首先需要匯入 System.Data 命名空間。 此命名空間包含與資料操作相關的各種類別和方法,包括 DataTable 類別。
using System.Data;
using System.Data;
Imports System.Data
接下來,您可以建立 DataTable 類別的一個實例。 最簡單的方法是使用預設的構建器,就像這樣:
DataTable dt = new DataTable();
DataTable dt = new DataTable();
Dim dt As New DataTable()
您也可以透過向建構函數傳遞字串參數來建立具有特定名稱的 DataTable:
DataTable dt = new DataTable("Employees");
DataTable dt = new DataTable("Employees");
Dim dt As New DataTable("Employees")
資料表方法
新增欄位
建立 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)
您可以在資料表中新增多個列,例如 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)
您也可以使用相同的方法在循環中一次新增多行 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
在上述程式碼中,我們新增了三行資料。
存取資料
您可以透過遍歷其 Rows 和 Columns 集合來存取儲存在 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
修改資料
您可以透過更新 DataTable 物件中的值來修改 DataRow 中的資料。 以下是如何更新特定員工年齡的範例:
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
刪除行
您可以透過呼叫 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
請記住,對 DataRow 呼叫 Delete 只會將該行標記為刪除。 您需要對 DataTable 呼叫 AcceptChanges 方法,以永久刪除已刪除的行。
管理多個表格
在某些情況下,您可能需要同時處理多個資料表。 您可以建立一個資料集變數來儲存數個 DataTable 物件,並管理它們之間的關係。
使用 LINQ 查詢資料
LINQ(語言整合查詢)是 C# 中的一項強大功能,它允許您從各種資料來源(包括 DataTable 物件)查詢資料。 若要將 LINQ 與 DataTables 一起使用,您需要匯入 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
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
使用 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
在本節中,我們將學習如何使用 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
接下來,建立一個輔助方法,將 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
現在,您可以使用 IronPDF 提供的HtmlToPdf class來渲染 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
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)
這將建立一個名為"Employees.pdf"的 PDF 文件,其中包含您的 DataTable 的內容,格式為表格。
結論
在本教學中,您學習了 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(語言整合查詢)是 C# 中強大的查詢工具,可對來自包括 DataTables 在內的各種來源的資料進行篩選、排序和操作,以簡化資料操作。
如何使用 DataView 過濾和排序 DataTable?
DataView 提供了一種便利的方法來創建 DataTable 的篩選或排序檢視。透過設定 RowFilter 和 Sort 屬性,您可以控制資料的顯示方式,這在 UI 元件中尤為有用。
如何安裝匯出 DataTables 為 PDF 的必要程式庫?
要安裝匯出 DataTables 為 PDF 的 IronPDF 程式庫,請使用 Visual Studio 中的套件管理控制台並執行命令:Install-Package IronPDF。



