La funcionalidad del motor de WorksheetChart Excel Infragistics Blazor le permite agregar representaciones de gráficos visuales de las tendencias de datos en las regiones de las celdas de una hoja de cálculo. Por ejemplo, si desea ver sus datos de Excel en una región de celdas visualizadas como una columna, una línea o más de 70 otros tipos de gráficos, esta función puede ayudarlo a lograrlo.
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using IgniteUI.Blazor.Controls;
namespaceInfragistics.Samples
{
publicclassProgram
{
publicstaticasync Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
// registering Ignite UI modules
builder.Services.AddIgniteUIBlazor(
typeof(IgbDataGridModule),
typeof(IgbCategoryChartModule)
);
await builder.Build().RunAsync();
}
}
}cs
@using Microsoft.AspNetCore.Components@using Microsoft.JSInterop@using Microsoft.JSInterop.WebAssembly@using Infragistics.Documents.Excel@using IgniteUI.Blazor.Controls@using System.Runtime.InteropServices.JavaScript@implements IDisposable
<divclass="container vertical"><divclass="options vertical"><button @onclick="ExportData">Save to Excel</button></div><divclass="container vertical"><IgbCategoryChartHeight="50%"Width="100%"DataSource="@ChartData"YAxisMinimumValue="0"XAxisInterval="1"ChartType="@CategoryChartType.Column"Brushes="#4f81bd, #c0504d, #9bbb59, #8064a2"Outlines="#4f81bd, #c0504d, #9bbb59, #8064a2"Thickness="0" /><IgbDataGridHeight="50%"Width="100%"DataSource="GridData"><IgbTextColumnField="Expense"Width="@("*>100")" /><IgbNumericColumnField="Jan"Width="@("*>75")" /><IgbNumericColumnField="Feb"Width="@("*>75")" /><IgbNumericColumnField="Mar"Width="@("*>75")" /><IgbNumericColumnField="Apr"Width="@("*>75")" /><IgbNumericColumnField="May"Width="@("*>75")" /><IgbNumericColumnField="Jun"Width="@("*>75")" /><IgbNumericColumnField="Jul"Width="@("*>75")" /><IgbNumericColumnField="Aug"Width="@("*>75")" /><IgbNumericColumnField="Sep"Width="@("*>75")" /><IgbNumericColumnField="Oct"Width="@("*>75")" /><IgbNumericColumnField="Nov"Width="@("*>75")" /><IgbNumericColumnField="Dec"Width="@("*>75")" /></IgbDataGrid></div></div>@code {
[Inject]
public IJSRuntime Runtime { get; set; }
public List<ExpenseGridInfo> GridData { get; set; }
public List<ExpenseChartInfo> ChartData { get; set; }
Random r = new Random();
protectedoverridevoidOnInitialized()
{
Workbook.InProcessRuntime = (IJSInProcessRuntime)this.Runtime;
InitData();
}
publicvoidInitData()
{
var months = newstring[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
var groups = newstring[] { "Heating", "Electricity", "Water", "Taxes" };
var expenseKey = "Expense";
var monthKey = "Month";
List<ExpenseGridInfo> _gridData = new List<ExpenseGridInfo>();
List<ExpenseChartInfo> _chartData = new List<ExpenseChartInfo>();
for (int i = 0; i < groups.Length; i++)
{
stringgroup = groups[i];
ExpenseGridInfo info = new ExpenseGridInfo() { Expense = group };
foreach(string month in months)
{
double x = i * 15 * Math.PI / 180;
double rand = r.Next(50, 100);
double heat = Math.Abs(Math.Cos(x)) * 300 + rand;
double ac = Math.Abs(Math.Sin(x)) * 500 + rand;
switch (group)
{
case"Heating": {
typeof(ExpenseGridInfo).GetProperty(month).SetValue(info, Math.Round(heat));
break;
}
case"Electricity":
{
typeof(ExpenseGridInfo).GetProperty(month).SetValue(info, Math.Round(ac));
break;
}
case"Water":
{
typeof(ExpenseGridInfo).GetProperty(month).SetValue(info, r.Next(100, 150));
break;
}
case"Taxes":
{
typeof(ExpenseGridInfo).GetProperty(month).SetValue(info, r.Next(700, 800));
break;
}
}
}
_gridData.Add(info);
}
foreach(string month in months)
{
ExpenseChartInfo data = new ExpenseChartInfo() { Month = month };
foreach(ExpenseGridInfo info in _gridData)
{
switch (info.Expense)
{
case"Heating":
{
data.Heat = (double)typeof(ExpenseGridInfo).GetProperty(month).GetValue(info);
break;
}
case"Electricity":
{
data.Electricity = (double)typeof(ExpenseGridInfo).GetProperty(month).GetValue(info);
break;
}
case"Water":
{
data.Water = (double)typeof(ExpenseGridInfo).GetProperty(month).GetValue(info);
break;
}
case"Taxes":
{
data.Taxes = (double)typeof(ExpenseGridInfo).GetProperty(month).GetValue(info);
break;
}
}
}
_chartData.Add(data);
}
this.GridData = _gridData;
this.ChartData = _chartData;
}
publicvoidExportData()
{
var workbook = new Workbook(WorkbookFormat.Excel2007);
var sheet = workbook.Worksheets.Add("Sheet1");
sheet.DefaultColumnWidth = 200 * 20;
int firstDataRow = 2;
var headerRow = sheet.Rows[firstDataRow - 1];
var props = typeof(ExpenseGridInfo).GetProperties();
for (int i = 0; i < props.Count(); i++)
{
System.Reflection.PropertyInfo prop = props[i];
headerRow.SetCellValue(i, prop.Name);
}
for (int i = 0; i < this.GridData.Count; i++)
{
var worksheetRow = sheet.Rows[i + firstDataRow];
ExpenseGridInfo item = this.GridData[i];
for (int j = 0; j < props.Length; j++)
{
System.Reflection.PropertyInfo info = props[j];
worksheetRow.SetCellValue(j, info.GetValue(item));
}
}
int indexRow = firstDataRow - 1;
int indexData = firstDataRow + this.GridData.Count - 1;
int indexHeader = props.Length - 1;
var tableRegion = new WorksheetRegion(sheet, indexRow, 0, indexData, indexHeader);
var table = sheet.Tables.Add(tableRegion.ToString(), true);
sheet.Rows[0].Height = 5000;
var chart = sheet.Shapes.AddChart(Documents.Excel.Charts.ChartType.ColumnClustered,
sheet.Rows[0].Cells[0], new Infragistics.Core.Point(0, 0),
sheet.Rows[0].Cells[props.Length - 1], new Infragistics.Core.Point(100, 100));
chart.SetSourceData(table.WholeTableRegion.ToString(), true);
chart.AxisCollection[Infragistics.Documents.Excel.Charts.AxisType.Category].AxisBetweenCategories = true;
var memStream = new System.IO.MemoryStream();
workbook.Save(memStream);
memStream.Position = 0;
var bytes = memStream.ToArray();
this.SaveFile(bytes, "ExelWorkbook.xlsx", string.Empty);
}
JSObject module;
bool moduleDownloaded = false;
publicasyncvoidSaveFile(byte[] bytes, string fileName, string mime)
{
if (Runtime is WebAssemblyJSRuntime wasmRuntime)
{
if (!moduleDownloaded)
{
module = await JSHost.ImportAsync("BlazorFastDownload", "../BlazorFastDownloadFile.js");
moduleDownloaded = true;
}
BlazorFastDownload.DownloadFile(fileName, mime, bytes);
}
elseif (Runtime is IJSInProcessRuntime inProc)
inProc.InvokeVoid("BlazorDownloadFile", fileName, mime, bytes);
}
publicvoidDispose()
{
if (moduleDownloaded && module != null)
{
module.Dispose();
}
}
publicclassExpenseGridInfo
{
publicstring Expense { get; set; }
publicdouble Jan { get; set; }
publicdouble Feb { get; set; }
publicdouble Mar { get; set; }
publicdouble Apr { get; set; }
publicdouble May { get; set; }
publicdouble Jun { get; set; }
publicdouble Jul { get; set; }
publicdouble Aug { get; set; }
publicdouble Sep { get; set; }
publicdouble Oct { get; set; }
publicdouble Nov { get; set; }
publicdouble Dec { get; set; }
}
publicclassExpenseChartInfo
{
publicstring Month { get; set; }
publicdouble Heat { get; set; }
publicdouble Electricity { get; set; }
publicdouble Water { get; set; }
publicdouble Taxes { get; set; }
}
}razor
// these methods are from:// https://www.meziantou.net/generating-and-downloading-a-file-in-a-blazor-webassembly-application.htmfunctionBlazorDownloadFile(filename, contentType, content) {
// Blazor marshall byte[] to a base64 string, so we first need to convert the string (content) to a Uint8Array to create the Filevar data = base64DecToArr(content);
// Create the URLvar file = new File([data], filename, { type: contentType });
var exportUrl = URL.createObjectURL(file);
// Create the <a> element and click on itvar a = document.createElement("a");
document.body.appendChild(a);
a.href = exportUrl;
a.download = filename;
a.target = "_self";
a.click();
// We don't need to keep the url, let's release the memory
URL.revokeObjectURL(exportUrl);
}
// Convert a base64 string to a Uint8Array. This is needed to create a blob object from the base64 string.// The code comes from: https://developer.mozilla.org/fr/docs/Web/API/WindowBase64/D%C3%A9coder_encoder_en_base64functionb64ToUint6(nChr) {
return nChr > 64 && nChr < 91 ? nChr - 65 : nChr > 96 && nChr < 123 ? nChr - 71 : nChr > 47 && nChr < 58 ? nChr + 4 : nChr === 43 ? 62 : nChr === 47 ? 63 : 0;
}
functionbase64DecToArr(sBase64, nBlocksSize) {
var sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length, nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = newUint8Array(nOutLen);
for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
nMod4 = nInIdx & 3;
nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
if (nMod4 === 3 || nInLen - nInIdx === 1) {
for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
}
nUint24 = 0;
}
}
return taBytes;
}
//# sourceMappingURL=BlazorDownloadFile.js.mapjs
/*
CSS styles are loaded from the shared CSS file located at:
https://static.infragistics.com/xplatform/css/samples/
*/css
¿Te gusta esta muestra? Obtenga acceso a nuestro kit de herramientas de Ignite UI for Blazor completo y comience a crear sus propias aplicaciones en minutos. Descárgalo gratis.
Uso
Para agregar un gráfico a una hoja de trabajo, debe utilizar el método AddChart de la colección de formas de la hoja de trabajo. En este método, puede especificar el tipo de gráfico que desea utilizar, la celda superior izquierda, la celda inferior derecha y los porcentajes de esas celdas que desea que ocupe el gráfico.
El método AddChart devuelve el elemento del gráfico de la hoja de trabajo que se agregará a la hoja de trabajo. Una vez que tenga esto, puede usar el método SetSourceData en el gráfico para establecer una dirección de celda de la región de celdas de la hoja de cálculo que desea usar como fuente de datos, así como si desea o no cambiar la asignación de columnas y filas al eje X e Y.
Hay más de 70 tipos de gráficos compatibles, incluidos Line, Area, IgbColumn y Pie.
El siguiente código demuestra cómo utilizar la función de gráficos de Excel. El siguiente fragmento agregará un gráfico de columnas entre la primera celda y la celda 13 en la primera fila de la hoja de trabajo. Luego, los datos de origen se configuran para los datos en la región de A2:M6, cambiando la asignación de columnas y filas para los ejes X e Y del gráfico de columnas:
var chart = sheet.Shapes.AddChart(Documents.Excel.Charts.ChartType.ColumnClustered,
sheet.Rows[0].Cells[0], new Core.Point(0, 0),
sheet.Rows[0].Cells[props.Length - 1], new Core.Point(100, 100));
chart.SetSourceData("A2:M6", true);
razor