C# DataTable(開發者的工作原理教程)
歡迎參加這個關於C# DataTables的教程。 一個DataTable是由.NET框架提供的強大的資料結構,允許您以表格格式儲存、操作和查詢資料。 在這個教程中,我們將探討C#中DataTables的基礎,包括建立和修改DataView進行篩選和排序。
到本教程結束時,您將對如何在C#應用程式中使用DataTables有很好的理解。 讓我們開始吧!
建立DataTable
要在C#中建立System.Data命名空間。 這個命名空間包含各種與資料操作相關的類和方法,其中包括DataTable類。
using System.Data;Imports System.DataImports System.Data接下來,您可以建立DataTable類的實例。 最簡單的方法是使用預設構造函式,像這樣:
DataTable dt = new DataTable();DataTable dt = new DataTable();Dim dt As New DataTable()Dim dt As New DataTable()您也可以通過向構造函式傳遞一個字串參數來建立具有特定名稱的DataTable。
DataTable dt = new DataTable("Employees");DataTable dt = new DataTable("Employees");Dim dt As New DataTable("Employees")Dim dt As 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);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)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)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 iFor 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在上面的程式碼中,我們新增了三個資料行。
存取資料
您可以通過遍歷其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 rowImports 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中的資料。 這裡有一個如何更新特定員工年齡的例子:
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 IfDim 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 IfDim employeeRow As DataRow = dt.Rows.Find(1)
If employeeRow IsNot Nothing Then
employeeRow.Delete()
dt.AcceptChanges() ' Commit the deletion
End If請注意,對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 rowImports 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 rowDataView:排序和篩選
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 rowViewDim 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 ClassImports 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中打開套件管理器控制台並運行以下命令:
安裝套件後,您可以開始在程式碼中導入所需的命名空間:
using IronPdf;
using System.IO;using IronPdf;
using System.IO;Imports IronPdf
Imports System.IOImports 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(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
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
htmlBuilder.AppendLine("</tr>")
Next
htmlBuilder.AppendLine("</table>")
Return htmlBuilder.ToString()
End FunctionPublic Shared Function ConvertDataTableToHtml(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
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
htmlBuilder.AppendLine("</tr>")
Next
htmlBuilder.AppendLine("</table>")
Return htmlBuilder.ToString()
End Function現在,您可以使用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(dt As DataTable, outputPath As String)
' Convert DataTable to HTML
Dim htmlTable As String = ConvertDataTableToHtml(dt)
' Create a new HTML to PDF renderer
Dim renderer As 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 SubPublic Shared Sub ExportDataTableToPdf(dt As DataTable, outputPath As String)
' Convert DataTable to HTML
Dim htmlTable As String = ConvertDataTableToHtml(dt)
' Create a new HTML to PDF renderer
Dim renderer As 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 SubDataTable並保存到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)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提供其功能的免費試用,允許您在購買前探索其能力。
Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。