Este breve tutorial guía sobre cómo crear una tabla dinámica en Excel usando C#. Para crear una tabla dinámica mediante programación, se proporciona código C# y una descripción detallada de modo que al final obtendrá un archivo XLSX (o XLS) que tiene una tabla dinámica sin usar ningún otro tercero -herramienta de fiesta. También contiene pasos que guían la adición de diferentes campos a diferentes áreas en la tabla dinámica.
Pasos para crear una tabla dinámica en C#
- Establezca el entorno para agregar Aspose.Cells for .NET desde el administrador de paquetes NuGet para crear una tabla dinámica
- Cree o cargue un workbook existente que tenga datos para la tabla dinámica
- Obtenga acceso al objetivo worksheet donde se agregará la tabla dinámica
- Cree una tabla dinámica y obtenga su instancia para su posterior procesamiento
- Configure la nueva tabla dinámica y agregue diferentes campos a la columna, fila y área de datos
- Guarde el libro de trabajo resultante que tiene una tabla dinámica.
Después de establecer el entorno para la generación de la tabla dinámica de C# Excel, aquí se describe que creamos un nuevo libro de trabajo aquí con los datos codificados; sin embargo, puede cargar un archivo de Excel existente que también contenga datos de destino. En los siguientes pasos, se describe con más detalle el proceso de creación de una tabla dinámica y luego su configuración. En los pasos finales, se agregan diferentes campos a diferentes áreas de la tabla dinámica, como la columna, la fila y los datos.
Código para crear una tabla dinámica en Excel usando C#
using System.IO; | |
using System.Text; | |
using Aspose.Cells; | |
namespace CreatePivotTableInExcelUsingCSharp | |
{ | |
class Program | |
{ | |
static void Main(string[] args) // Main function to set width of cell in CSharp | |
{ | |
// Instantiate the license to remove trial version watermark in the output Excel file | |
Aspose.Cells.License licForCells= new Aspose.Cells.License(); | |
licForCells.SetLicense("Aspose.Cells.lic"); | |
// Set the hard-coded data. You may use an existing Excel file also if required | |
byte[] SrcDataByteArray = Encoding.ASCII.GetBytes( | |
$@"City,Product,Sales | |
Paris,Cream,2300 | |
Paris,Lotion,1600 | |
Tunis,Cream,900 | |
Tunis,Lotion,1400 | |
Tunis,Cream,3090 | |
Tunis,Lotion,6000 | |
Paris,Cream,4320" ); | |
// Create a memory stream from the source data | |
MemoryStream dataStream = new MemoryStream( SrcDataByteArray ); | |
// Create LoadOptions class object to load the comma-separated data given above | |
LoadOptions loadOptions = new LoadOptions(LoadFormat.Csv); | |
// Instantiate a workbook class object having above mentioned data | |
Workbook wbCSV = new Workbook(dataStream, loadOptions); | |
// Get access to the first worksheet in the collection | |
Worksheet targetSheet = wbCSV.Worksheets[0]; | |
// Get collection of pivot tables in the target worksheet | |
Aspose.Cells.Pivot.PivotTableCollection pvTablesCollection = targetSheet.PivotTables; | |
// Get pivot table index after adding a new pivot table by provding source data range and destination cell | |
int iNewPivotTable = pvTablesCollection.Add("=A1:C8", "F3", "MyPivotTable"); | |
// Get the instance of newly added pivot table for further processing | |
Aspose.Cells.Pivot.PivotTable newPivotTable = pvTablesCollection[iNewPivotTable]; | |
// Hide the grand total for rows in the output Excel file | |
newPivotTable.RowGrand = false; | |
// Add the first field to the column area | |
newPivotTable.AddFieldToArea(Aspose.Cells.Pivot.PivotFieldType.Column, 0); | |
// Add the second field to the row area | |
newPivotTable.AddFieldToArea(Aspose.Cells.Pivot.PivotFieldType.Row, 1); | |
// Add the third field to the data area | |
newPivotTable.AddFieldToArea(Aspose.Cells.Pivot.PivotFieldType.Data, 2); | |
// Saving the output Excel file with pivot table | |
wbCSV.Save("OutputPivotTable.xlsx"); | |
System.Console.WriteLine("Done"); | |
} | |
} | |
} |
Este código de muestra demuestra cómo crear una tabla dinámica en C# proporcionando el rango de datos y la celda de destino donde se colocará la tabla dinámica junto con el nombre de la tabla dinámica. La clase pivotTable tiene una función AddFieldToArea() que se usa para arrastrar diferentes campos a diferentes áreas usando pivotFieldType como Columna, Fila o Datos junto con el número de campo en el rango de datos seleccionado. También puede usar otra página pivotFieldType si es necesario.
En este artículo, hemos aprendido a agregar una tabla dinámica de Excel en C#. Si desea aprender a exportar datos en una lista a Excel, consulte el artículo sobre cómo exportar datos de lista a Excel en C#.