Pruebe en producción sin marcas de agua.
Funciona donde lo necesite.
Obtén 30 días de producto totalmente funcional.
Ténlo en funcionamiento en minutos.
Acceso completo a nuestro equipo de asistencia técnica durante la prueba del producto
Bienvenido a este tutorial sobre C# DataTables. Un DataTable
es una estructura de datos poderosa proporcionada por el marco .NET, que te permite almacenar, manipular y consultar datos en un formato tabular. En este tutorial, exploraremos los aspectos básicos de DataTables en C#, incluyendo la creación y modificación de DataTables
, la adición de columnas y filas, la consulta de datos y el uso de DataView
para filtrar y ordenar.
Al final de este tutorial, tendrás una buena comprensión de cómo utilizar DataTables
en tus aplicaciones C#. ¡Comencemos!
Para crear un DataTable
en C#, primero necesitas importar el espacio de nombres System.Data
. Este espacio de nombres contiene varias clases y métodos relacionados con la manipulación de datos, incluida la clase DataTable
.
using System.Data;
using System.Data;
Imports System.Data
A continuación, puede crear una instancia de la clase DataTable
. La forma más sencilla de hacerlo es utilizando el constructor por defecto, así:
DataTable dt = new DataTable();
DataTable dt = new DataTable();
Dim dt As New DataTable()
También puedes crear un DataTable
con un nombre específico pasando un parámetro de cadena al constructor:
DataTable dt = new DataTable("Employees");
DataTable dt = new DataTable("Employees");
Dim dt As New DataTable("Employees")
Una vez que haya creado una DataTable, puede empezar a añadirle columnas. Para agregar una columna, primero necesitas crear una instancia de la clase DataColumn
y establecer sus propiedades, como ColumnName
y DataType
.
He aquí un ejemplo de cómo añadir tres columnas a una 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)
Puedes agregar múltiples columnas como la columna Id
en la tabla de datos.
Después de definir las columnas, puedes comenzar a agregar filas al DataTable
. Para agregar una fila, necesitas crear una nueva instancia de la clase DataRow
y completar sus campos con los datos requeridos.
Aquí tienes un ejemplo de cómo agregar una nueva fila a un 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)
También puedes añadir múltiples filas de DataTable
a la vez utilizando el mismo método en un bucle.
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
En el código anterior, hemos añadido tres filas de datos.
Puede acceder a los datos almacenados en un DataTable
iterando a través de sus colecciones de Rows
y Columns
. Aquí tienes un ejemplo de cómo mostrar el contenido de un DataTable
en la consola:
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
Puedes modificar los datos en un DataTable
actualizando los valores en sus objetos DataRow
. He aquí un ejemplo de cómo actualizar la edad de un empleado concreto:
DataRow employeeRow = dt.Rows.Find(1); // Find the row with the specified primary key
if (employeeRow != null)
{
employeeRow ["Age"] = 35;
}
DataRow employeeRow = dt.Rows.Find(1); // Find the row with the specified primary key
if (employeeRow != null)
{
employeeRow ["Age"] = 35;
}
Dim employeeRow As DataRow = dt.Rows.Find(1) ' Find the row with the specified primary key
If employeeRow IsNot Nothing Then
employeeRow ("Age") = 35
End If
Puedes eliminar una fila de un DataTable llamando al método Delete en un objeto DataRow
:
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
Ten en cuenta que llamar a Delete
en un DataRow
solo marca la fila para eliminación. Necesitas llamar al método AcceptChanges
en el DataTable
para eliminar de manera permanente las filas borradas.
En algunos casos, puede que necesite trabajar con varias tablas de datos simultáneamente. Puede crear una variable dataset para almacenar varios objetos DataTable y gestionar las relaciones entre ellos.
LINQ (Language Integrated Query) es una función poderosa en C# que te permite consultar datos de diversas fuentes de datos, incluyendo objetos DataTable
. Para usar LINQ con DataTables, necesitas importar el espacio de nombres System.Linq
. He aquí un ejemplo de cómo filtrar empleados mayores de 25 años utilizando LINQ:
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
es otra clase útil proporcionada por el espacio de nombres System.Data
que te permite crear una vista ordenada o filtrada de un DataTable
. Esto es especialmente útil cuando necesitas mostrar los datos en un control de interfaz de usuario como un DataGridView
. También podemos realizar el enlace de datos para agregar datos al control DataGridView
desde un DataTable
.
He aquí un ejemplo de cómo crear un DataView para filtrar y ordenar los empleados en función de su edad:
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 es un potente convertidor de HTML a PDF, lleno de funciones de manipulación de PDF fáciles de usar, que permite a los desarrolladores crear, leer y editar documentos PDF dentro de aplicaciones .NET.
using IronPdf;
class Program
{
static void Main(string [] args)
{
var renderer = new ChromePdfRenderer();
// 1. 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");
// 2. 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");
// 3. 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();
// 1. 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");
// 2. 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");
// 3. 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()
' 1. 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")
' 2. 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")
' 3. 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
En esta sección, aprenderemos cómo exportar un DataTable
a un documento PDF usando IronPDF.
En primer lugar, debe instalar el paquete IronPDF NuGet. Abra la consola del gestor de paquetes en Visual Studio y ejecute el siguiente comando:
Install-Package IronPdf
Una vez instalado el paquete, puede empezar importando los espacios de nombres necesarios en su código:
using IronPdf;
using System.IO;
using IronPdf;
using System.IO;
Imports IronPdf
Imports System.IO
A continuación, cree un método auxiliar que convierta DataTable en una tabla HTML, ya que IronPDF utiliza HTML para representar el contenido de los documentos 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
Ahora, puedes usar la clase HtmlToPdf
proporcionada por IronPDF para renderizar la tabla HTML y guardarla como un archivo 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
El método ExportDataTableToPdf
crea un DataTable
a partir de la tabla HTML y lo guarda en el archivo PDF.
Finalmente, llama al método ExportDataTableToPdf
con los parámetros apropiados para exportar tu DataTable
:
string pdfOutputPath = "Employees.pdf";
ExportDataTableToPdf(dt, pdfOutputPath);
string pdfOutputPath = "Employees.pdf";
ExportDataTableToPdf(dt, pdfOutputPath);
Dim pdfOutputPath As String = "Employees.pdf"
ExportDataTableToPdf(dt, pdfOutputPath)
Esto creará un archivo PDF llamado "Employees.pdf" que contiene el contenido de su DataTable
en un formato tabular.
En este tutorial, has aprendido los conceptos básicos de DataTables en C# y cómo exportar un DataTable
a un documento PDF usando la biblioteca IronPDF. Al incorporar la columna de clave principal, las variables del conjunto de datos y DataView para filtrar y ordenar, tendrá un mayor control y flexibilidad sobre sus datos. Ahora debería tener un buen conocimiento de DataTables y de cómo utilizar IronPDF junto con DataTables para crear informes PDF de aspecto profesional en sus aplicaciones C#.
IronPDF ofrece una prueba gratuita de sus funciones, permitiéndote explorar sus capacidades antes de comprometerte a una compra.