C# 数据表(开发者教程)
欢迎来到这个 C# DataTables 教程。 .NET框架提供的DataTable是一个强大的数据结构,允许您以表格格式存储、操作和查询数据。 在本教程中,我们将探索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现在,您可以使用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(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 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。