To add the chart to the Excel spreadsheet it looks like I need to call worksheet.Pictures.AddPicture which requires a stream object. I'm struggling to convert the chart to a stream. I've tried using the chart event AfterExport as suggested in thread Id 151623 but like David I'm unable to get it to fire, I also suspect that it would download the chart image to the users browser which I want to avoid as I want to download just the generated Excel spreadsheet.
Neither the before or after events fire for me in this sample.
@page "/"
@using Syncfusion.Blazor.Charts
@using Syncfusion.Blazor.Buttons
@using System.IO
@using System.Text.RegularExpressions
@using System.Drawing
<SfButton OnClick="@ChartDownload">Download Chart</SfButton>
<br />
<br />
<br />
<SfChart @ref="@ChartObj" EnableCanvas="false">
<ChartEvents AfterExport=@AfterGetChartImage BeforeExport="BeforeGetChartImage"></ChartEvents>
<ChartPrimaryXAxis LabelFormat="n0" Minimum="15" Maximum="19" Interval="1"></ChartPrimaryXAxis>
<ChartSeriesCollection>
<ChartSeries DataSource="@chartData" XName="xValue" YName="yValue1" Opacity="1" Fill="green" Width=2 Type="ChartSeriesType.Column">
</ChartSeries>
<ChartSeries DataSource="@chartData" XName="xValue" YName="yValue2" Opacity="1" Fill="blueviolet" Width=2 Type="ChartSeriesType.Column">
</ChartSeries>
</ChartSeriesCollection>
</SfChart>
@code{
SfChart ChartObj;
public class DoubleData
{
public double xValue { get; set; }
public double yValue1 { get; set; }
public double yValue2 { get; set; }
}
public List<DoubleData> chartData = new List<DoubleData>
{
new DoubleData { xValue = 16, yValue1 = 2, yValue2= 7},
new DoubleData { xValue = 17, yValue1 = 7, yValue2 = 8 },
new DoubleData { xValue = 18, yValue1 = 10, yValue2 = 24 },
};
void BeforeGetChartImage(IExportEventArgs Arg)
{
}
void AfterGetChartImage(IAfterExportEventArgs Arg)
{
var dataURL = Arg.DataUrl;
var base64Data = Regex.Match(dataURL, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
MemoryStream stream = new MemoryStream(binData);
var image = Image.FromStream(stream);
image.Save("chartmemoryimage.png", System.Drawing.Imaging.ImageFormat.Png);
}
void ChartDownload()
{
ChartObj.Export(ExportType.PNG, "Chart-Mem-dwnld");
}
}