Cómo utilizar C# para convertir Datatable a CSV

Puede exportar una tabla de datos a CSV con IronXL tomando una tabla de datos existente y convirtiéndola a CSV en sólo unos pocos pasos. Este artículo pretende mostrarle un ejemplo rápido al respecto.


Primer paso

1. Añadir IronXL Free

Antes de poder utilizar IronXL en tus aplicaciones, necesitas tenerlo instalado. Por suerte, ofrecen muchas opciones para instalar IronXL en sus proyectos.

Descárguelo desde su sitio web utilizando el siguiente enlace: https://ironsoftware.com/csharp/excel/docs/

o

  • En Visual Studio, seleccione el menú Proyecto
  • Haga clic en Gestionar paquetes NuGet
  • Buscar IronXL.Excel
  • Haga clic en Instalar
Install-Package IronXL.Excel
Paquete IronXL.Excel NuGet
Figura 1 - Paquete NuGet IronXL.Excel

Tutorial

2. Crear y exportar una tabla de datos a CSV

Ahora estás listo.

Primero importa el espacio de nombres IronXL

using IronXL;
using IronXL;
Imports IronXL
VB   C#

A continuación, añada el siguiente código:

/**
Save a datatable to CSV
anchor-create-and-export-datatable-to-csv
**/
private void button6_Click(object sender, EventArgs e)
{
    DataTable table = new DataTable();
    table.Columns.Add("Example_DataSet", typeof(string));

    table.Rows.Add("0");
    table.Rows.Add("1");
    table.Rows.Add("2");
    table.Rows.Add("3");
    table.Rows.Add("1");
    table.Rows.Add("2");
    table.Rows.Add("3");

    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
    wb.Metadata.Author = "OJ";
    WorkSheet ws = wb.DefaultWorkSheet;

    int rowCount = 1;
    foreach (DataRow row in table.Rows)
    {

        ws ["A" + (rowCount)].Value = row [0].ToString();

        rowCount++;
    }

    wb.SaveAsCsv("Save_DataTable_CSV.csv", ";"); //  Guardado como : Guardar_Tabla_de_datos_CSV.Hoja1.csv
}
/**
Save a datatable to CSV
anchor-create-and-export-datatable-to-csv
**/
private void button6_Click(object sender, EventArgs e)
{
    DataTable table = new DataTable();
    table.Columns.Add("Example_DataSet", typeof(string));

    table.Rows.Add("0");
    table.Rows.Add("1");
    table.Rows.Add("2");
    table.Rows.Add("3");
    table.Rows.Add("1");
    table.Rows.Add("2");
    table.Rows.Add("3");

    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
    wb.Metadata.Author = "OJ";
    WorkSheet ws = wb.DefaultWorkSheet;

    int rowCount = 1;
    foreach (DataRow row in table.Rows)
    {

        ws ["A" + (rowCount)].Value = row [0].ToString();

        rowCount++;
    }

    wb.SaveAsCsv("Save_DataTable_CSV.csv", ";"); //  Guardado como : Guardar_Tabla_de_datos_CSV.Hoja1.csv
}
'''
'''Save a datatable to CSV
'''anchor-create-and-export-datatable-to-csv
'''*
Private Sub button6_Click(ByVal sender As Object, ByVal e As EventArgs)
	Dim table As New DataTable()
	table.Columns.Add("Example_DataSet", GetType(String))

	table.Rows.Add("0")
	table.Rows.Add("1")
	table.Rows.Add("2")
	table.Rows.Add("3")
	table.Rows.Add("1")
	table.Rows.Add("2")
	table.Rows.Add("3")

	Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)
	wb.Metadata.Author = "OJ"
	Dim ws As WorkSheet = wb.DefaultWorkSheet

	Dim rowCount As Integer = 1
	For Each row As DataRow In table.Rows

		ws ("A" & (rowCount)).Value = row (0).ToString()

		rowCount += 1
	Next row

	wb.SaveAsCsv("Save_DataTable_CSV.csv", ";") '  Guardado como : Guardar_Tabla_de_datos_CSV.Hoja1.csv
End Sub
VB   C#

El código anterior crea una tabla de datos, luego crea un nuevo libro de trabajo especificando 'OJ' como su propietario / creador. A continuación sigue un bucle foreach que inserta los datos de la tabla de datos en la hoja de cálculo de Excel. Por último, el método SaveAsCsv se utiliza para exportar la tabla de datos a csv.

La hoja de cálculo Excel de salida tiene el siguiente aspecto:

Salida de tabla de datos a CSV
Figura 2 - Salida de datos a CSV

Acceso rápido a la biblioteca

Documentación de referencia de la API IronXL

Learn more and share how to merge, unmerge, and work with cells in Excel spreadsheets using the handy Documentación de referencia de la API IronXL.

Documentación de referencia de la API IronXL