AYUDA .NET

C# DataTable (Tutorial de Funcionamiento para Desarrolladores)

Actualizado mayo 8, a. m.
Compartir:

Bienvenido a este tutorial sobre C# DataTables. Una DataTable es una potente estructura de datos proporcionada por el framework .NET, que permite almacenar, manipular y consultar datos en formato tabular. En este tutorial, exploraremos los conceptos 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, usted tendrá una buena comprensión de cómo utilizar DataTables en sus aplicaciones C#. Comencemos!

Creación de una DataTable

Para crear una DataTable en C#, primero hay que importar el espacio de nombres System.Data. Este espacio de nombres contiene varias clases y métodos relacionados con la manipulación de datos, incluyendo la clase DataTable.

 using System.Data;
 using System.Data;
Imports System.Data
VB   C#

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()
VB   C#

También puedes crear una 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")
VB   C#

Métodos de DataTable

Añadir columnas

Una vez que haya creado una DataTable, puede empezar a añadirle columnas. Para añadir una columna, primero hay que 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);
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Puede añadir varias columnas como la columna Id en la tabla de datos.

Añadir filas de datos

Una vez definidas las columnas, puede empezar a añadir filas a la DataTable. Para añadir una fila, es necesario crear una nueva instancia de la clase DataRow y rellenar sus campos con los datos requeridos.

He aquí un ejemplo de cómo añadir una nueva fila a una 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);
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

También puede añadir varias 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
VB   C#

En el código anterior, hemos añadido tres filas de datos.

Acceso a los datos

Puedes acceder a los datos almacenados en una DataTable iterando a través de sus colecciones Rows y Columns. He aquí un ejemplo de cómo mostrar el contenido de una 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
VB   C#

Modificación de datos

Puede modificar los datos de una DataTable actualizando los valores de 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
VB   C#

Borrar filas

Puede eliminar una fila de una DataTable llamando al método Delete de 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
VB   C#

Tenga en cuenta que llamar a Delete en una DataRow sólo marca la fila para su eliminación. Necesitas llamar al método AcceptChanges en la DataTable para eliminar permanentemente las filas borradas.

Gestión de varias tablas

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.

Consulta de datos con LINQ

LINQ (Idioma Consulta integrada) es una potente función de C# que permite consultar datos de diversas fuentes de datos, incluidos los objetos DataTable. Para utilizar LINQ con DataTables, es necesario 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"]);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

DataView: Ordenar y filtrar

DataView es otra clase útil proporcionada por el espacio de nombres System.Data que permite crear una vista ordenada o filtrada de una DataTable. Esto es especialmente útil cuando se necesita mostrar los datos en un control de interfaz de usuario como un DataGridView. También podemos hacer data binding para añadir datos al control DataGridView desde una 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
VB   C#

Exportación de DataTable a PDF con IronPDF

IronPDF es un potente HTML a PDF repleto de funciones de manipulación de PDF fáciles de usar, permite a los desarrolladores crear, leer y editar documentos PDF en 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
VB   C#

En esta sección, aprenderemos cómo exportar una DataTable a un documento PDF utilizando 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
VB   C#

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
VB   C#

Ahora, puede utilizar la función HtmlToPdf proporcionada por IronPDF para representar la tabla HTML y guardarla como 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
VB   C#

El método ExportDataTableToPdf crea una DataTable a partir de la tabla HTML y la guarda en el archivo PDF.

Por último, llama al método ExportDataTableToPdf con los parámetros adecuados 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)
VB   C#

Esto creará un fichero PDF llamado "Empleados.pdf" que contendrá el contenido de su TablaDatos en formato tabular.

C# DataTable (Tutorial de cómo funciona para desarrolladores) - Figura 1

Conclusión

En este tutorial, usted ha aprendido los conceptos básicos de DataTables en C# y cómo exportar un DataTable a un documento PDF utilizando 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 un prueba gratuitapara que puedas explorar sus funciones y capacidades antes de comprometerte a comprarlo.

< ANTERIOR
Instalar NuGet Powershell (Tutorial de cómo funciona para desarrolladores)
SIGUIENTE >
Cómo utilizar .NET Fiddle en C#

¿Listo para empezar? Versión: 2024.8 acaba de salir

Descarga gratuita de NuGet Descargas totales: 10,439,034 Ver licencias >