Este breve tutorial orienta sobre como criar uma tabela dinâmica no Excel usando C#. Para criar uma tabela dinâmica programaticamente C#, o código e a descrição detalhada são fornecidos de forma que, no final, você obtenha um arquivo XLSX (ou XLS) com uma tabela dinâmica sem usar nenhum outro terceiro -ferramenta de festa. Ele também contém etapas que orientam a adição de campos diferentes a áreas diferentes na tabela dinâmica.
Etapas para criar uma tabela dinâmica em C#
- Estabeleça o ambiente para adicionar Aspose.Cells for .NET do gerenciador de pacotes NuGet para criar uma tabela dinâmica
- Crie ou carregue um workbook existente com dados para a tabela dinâmica
- Obtenha acesso ao destino worksheet onde a tabela dinâmica deve ser adicionada
- Crie uma tabela dinâmica e obtenha sua instância para processamento adicional
- Configure a nova tabela dinâmica e adicione campos diferentes à coluna, linha e área de dados
- Salve a pasta de trabalho resultante com uma tabela dinâmica nela
Depois de estabelecer o ambiente para a geração da tabela dinâmica C# Excel é descrito aqui, de modo que criamos uma nova pasta de trabalho aqui com os dados codificados, mas você pode carregar um arquivo Excel existente também com dados de destino. Nas próximas etapas, ele descreve melhor o processo de criação de uma tabela dinâmica e, em seguida, sua configuração. Nas etapas finais, diferentes campos são adicionados a diferentes áreas da tabela dinâmica, como coluna, linha e dados.
Código para criar tabela dinâmica no 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 exemplo demonstra como criar uma tabela dinâmica em C# fornecendo o intervalo de dados e a célula de destino onde a tabela dinâmica deve ser colocada junto com o nome da tabela dinâmica. A classe pivotTable tem uma função AddFieldToArea() que é usada para arrastar diferentes campos para diferentes áreas usando pivotFieldType como Column, Row ou Data junto com o número do campo no intervalo de dados selecionado. Você também pode usar outra página pivotFieldType, se necessário.
Neste artigo, aprendemos a adicionar tabela dinâmica do Excel em C#. Se você quiser aprender a exportar dados em uma lista para o Excel, consulte o artigo em como exportar dados de lista para o Excel em C#.