Exporting in Windows Forms Chart

18 Nov 201824 minutes to read

The Windows Forms Chart control supports exporting chart content to various formats, including images, Word, PDF, Grid, Excel, and CSV. Use Syncfusion DocIO, PDF, Grid, and XlsIO libraries to export to the corresponding formats.

Exporting as an image

Use the SaveImage method to export the chart to an image file. The image format is determined by the extension specified in the file name.

private string fileName;
fileName = Application.StartupPath + "\\chartExport";
fileName = fileName + ".gif";
this.chartControl.SaveImage(fileName);
// Launches the file. 
System.Diagnostics.Process.Start(exportFileName);
Private fileName As String
fileName = Application.StartupPath + "\chartExport"
fileName = fileName + ".gif"
Me.chartControl.SaveImage(fileName)
' Launches the file. 
System.Diagnostics.Process.Start(exportFileName)

Based on the filename extension the chart has built-in support to save the image in the following formats.

File Extension File Type
.bmp BMP
.jpg JPEG
.jpeg JPEG
.gif GIF
.tiff TIFF
.Wmf WMF
.emf EMF
.svg SVG (Scalable Vector Graphics)
.eps Post Script

If the specified extension is none of the above, the chart is exported as a bitmap. At runtime, the chart can also be saved using the save option in the Chart Toolbar.

Editable text support for EPS images

Set the EditableText property of the ToPostScript class to true to export an EPS image with editable text.

ToPostScript toPostScript = new ToPostScript();
toPostScript.EditableText = true;
using(Graphics g = toPostScript.GetRealGraphics(this.chartControl.Size))
{
    this.chartControl.Draw(g, this.chartControl.Size);
    g.Dispose();
    toPostScript.Save("EditableTextChart.eps");
}
Dim toPostScript As New ToPostScript()
toPostScript.EditableText = True
Using g As Graphics = toPostScript.GetRealGraphics(Me.chartControl.Size)
    Me.chartControl.Draw(g, Me.chartControl.Size)
    g.Dispose();
    toPostScript.Save("EditableTextChart.eps")
End Using

The following image illustrates the chart EPS image text editing in Adobe Illustrator.

Chart exported as an EPS image

Enabling EditableText property does not support chart text wrapping and formatting in the exported EPS image.

Exporting to word doc

Use Syncfusion DocIO to export the chart to a Word document as an image. The chart control provides APIs to convert it to an image, while DocIO lets you insert this image into a Word Document file programmatically.

Chart exported to a Word document

Given below are the steps that will guide you through this process.

  1. Add the Syncfusion.DocIO.Base and Syncfusion.DocIO.Windows assemblies.

  2. Add the namespace Syncfusion.DocIO and Syncfusion.DocIO.DLS in your form.

    using Syncfusion.DocIO;
    using Syncfusion.DocIO.DLS;
    Imports Syncfusion.DocIO
    Imports Syncfusion.DocIO.DLS
  3. Add the code snippet that is given below in your form.

    string fileName=Application.StartupPath+"\\chartExport";
    string exportFileName = fileName + ".doc";
    string file = fileName + ".gif";
    this.chartControl.SaveImage(file);
    // Create a new document.
    WordDocument document = new WordDocument();
    // Adding a new section to the document.
    IWSection section = document.AddSection();
    // Adding a paragraph to the section.
    IWParagraph paragraph = section.AddParagraph();                                                
    // Writing text.
    paragraph.AppendText( "Essential Chart" );
    // Adding a new paragraph.                
    paragraph = section.AddParagraph();
    paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DLS.HorizontalAlignment.Center;
    // Inserting chart.
    paragraph.AppendPicture( Image.FromFile(file));
    // Save the Document to disk.
    document.Save(exportFileName , Syncfusion.DocIO.FormatType.Doc );
    // Launches the file.                         
    System.Diagnostics.Process.Start(exportFileName);
    Dim fileName As String =Application.StartupPath & "\chartExport"
    Dim exportFileName As String = fileName & ".doc"
    Dim file As String = fileName & ".gif"
    Me.chartControl.SaveImage(file)
    ' Create a new document.
    Dim document As WordDocument = New WordDocument()
    ' Adding a new section to the document.
    Dim section As IWSection = document.AddSection()
    ' Adding a paragraph to the section.
    Dim paragraph As IWParagraph = section.AddParagraph()
    ' Writing text.
    paragraph.AppendText("Essential Chart")
    ' Adding a new paragraph.                
    paragraph = section.AddParagraph()
    paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DLS.HorizontalAlignment.Center
    ' Inserting chart.
    paragraph.AppendPicture(Image.FromFile(file))
    ' Save the Document to disk.
    document.Save(exportFileName, Syncfusion.DocIO.FormatType.Doc)
    ' Launches the file.                         
    System.Diagnostics.Process.Start(exportFileName)

Exporting to grid

Use Syncfusion Grid to display the exported chart image in a grid cell. The chart control provides APIs to convert it to an image, while the Grid will let you insert this image into any specific cell.

Chart exported to a Grid cell

The steps that are given below will guide you through the process.

  1. Add the Syncfusion.Grid.Base and Syncfusion.Grid.Windows assemblies.

  2. Add a form (Form2) to hold the Grid control in which the chart is to be exported.

  3. Drag a grid control onto the Form2.

  4. Add the namespace Syncfusion.Windows.forms.Grid in Form2.

    using Syncfusion.Windows.Forms.Grid;
    Imports Syncfusion.Windows.Forms.Grid
  5. Add the code snippet that is given below in Form2 to get the chart data into the grid.

    // Creates a new instance of the ImageList class.
    ImageList image = new ImageList();
    // Adds the image to the Image collection of the ImageList.
    image.Images.Add(Image.FromFile(this.Name));
    // Specify the size of the image.
    image.ImageSize = new Size(256, 256);
    // Set the imageList of the cell.
    this.gridControl[1,1].ImageList = image;
    // Specify the index for the image to be displayed.
    this.gridControl[1, 1].ImageIndex = 0;
    // Specify the row and column height of the cell.
    this.gridControl.RowHeights[1] = 300;
    this.gridControl.ColWidths[1] = 300;
    // Specify the image size mode.
    this.gridControl[1, 1].ImageSizeMode = GridImageSizeMode.CenterImage;
    ' Creates a new instance of the ImageList class.
    Dim image As ImageList = New ImageList()
    ' Adds the image to the Image collection of the ImageList.
    image.Images.Add(Image.FromFile(Me.Name))
    ' Specify the size of the image.
    image.ImageSize = New Size(256, 256)
    ' Set the imageList of the cell.
    Me.gridControl(1,1).ImageList = image
    ' Specify the index for the image to be displayed.
    Me.gridControl(1, 1).ImageIndex = 0
    ' Specify the row and column height of the cell.
    Me.gridControl.RowHeights(1) = 300
    Me.gridControl.ColWidths(1) = 300
    ' Specify the image size mode.
    Me.gridControl(1, 1).ImageSizeMode = GridImageSizeMode.CenterImage
  6. Add the code that is given below in the form with the chart control to be exported.

    private Form2 gridForm;
    this.gridForm= new Form2();
    string fileName=Application.StartupPath+"\\chartExport";
    string file = fileName + ".gif";
    if(!System.IO.File.Exists(file))
    this.chartControl.SaveImage(file);
    // Specify the filename as the name of the form.
    gridForm.Name = file;
    // Shows the form with grid control with the chart exported.
    gridForm.ShowDialog();
    Private gridForm As Form2
    Me.gridForm= New Form2()
    Dim fileName As String =Application.StartupPath & "\chartExport"
    Dim file As String = fileName & ".gif"
    If (Not System.IO.File.Exists(file)) Then
    Me.chartControl.SaveImage(file)
    End If
    ' Specify the filename as the name of the form.
    gridForm.Name = file
    ' Shows the form with grid control with the chart exported.
    gridForm.ShowDialog()

Exporting to excel

Use Syncfusion XlsIO to export chart data to an Excel workbook and create an Excel chart from the exported data.

Chart data exported to Excel

Add the Syncfusion.XlsIO namespace.

Given below are the steps that will guide you through this process.

  1. Add the Syncfusion.XLsIO.Base and Syncfusion.XLsIO.Windows assemblies.

  2. Add the namespace Syncfusion.XLsIO in your form.

    using Syncfusion.XlsIO;
    Imports Syncfusion.XlsIO
  3. Add the code snippet that is given below in your form.

    string exportFileName = Application.StartupPath+"\\chartExport" + ".xls";                                    
    // A new workbook with a worksheet should be created.
    IWorkbook chartBook = ExcelUtils.CreateWorkbook(1);
    IWorksheet sheet = chartBook.Worksheets[0];
    // Fill the worksheet with chart data.
    for(int i=1;i<=5;i++)
    {
    	sheet.Range[i,1].Number = this.chartControl.Series[0].Points[i-1].X;
    	sheet.Range[i,2].Number = this.chartControl.Series[0].Points[i-1].YValues[0];
    }
    // Create a chart worksheet.
    IChart chart = chartBook.Charts.Add("Essential Chart");
    // Specify the title of the Chart.
    chart.ChartTitle = "Essential Chart";
    // Initialize a new series instance and add it to the series collection of the chart.
    IChartSerie series = chart.Series.Add();
    // Specify the chart type of the series.
    series.SerieType = ExcelChartType.Column_Clustered;
    // Specify the name of the series. This will be displayed as the text of the legend.
    series.Name = "Sample Series";
    // Specify the value ranges for the series.
    series.Values = sheet.Range["B1:B5"];
    // Specify the Category labels for the series.
    series.CategoryLabels = sheet.Range["A1:A5"];
    // Make the chart as active sheet.
    chart.Activate();
    // Save the Chart book.
    chartBook.SaveAs(exportFileName);
    chartBook.Close();
    ExcelUtils.Close();
    // Launches the file.
    System.Diagnostics.Process.Start(exportFileName);
    Dim exportFileName As String = Application.StartupPath & "\chartExport" & ".xls"
    ' A new workbook with a worksheet should be created.
    Dim chartBook As IWorkbook = ExcelUtils.CreateWorkbook(1)
    Dim sheet As IWorksheet = chartBook.Worksheets(0)
    ' Fill the worksheet with chart data.
    For i As Integer = 1 To 5
    sheet.Range(i,1).Number = Me.chartControl.Series(0).Points(i-1).X
    sheet.Range(i,2).Number = Me.chartControl.Series(0).Points(i-1).YValues(0)
    Next i
    ' Create a chart worksheet.
    Dim chart As IChart = chartBook.Charts.Add("Essential Chart")
    ' Specify the title of the Chart.
    chart.ChartTitle = "Essential Chart"
    ' Initialize a new series instance and add it to the series collection of the chart.
    Dim series As IChartSerie = chart.Series.Add()
    ' Specify the chart type of the series.
    series.SerieType = ExcelChartType.Column_Clustered
    ' Specify the name of the series. This will be displayed as the text of the legend.
    series.Name = "Sample Series"
    ' Specify the value ranges for the series.
    series.Values = sheet.Range("B1:B5")
    ' Specify the Category labels for the series.
    series.CategoryLabels = sheet.Range("A1:A5")
    ' Make the chart as active sheet.
    chart.Activate()
    ' Save the Chart book.
    chartBook.SaveAs(exportFileName)
    chartBook.Close()
    ExcelUtils.Close()
    ' Launches the file. 
    System.Diagnostics.Process.Start(exportFileName)

Exporting to PDF

Use Syncfusion PDF to export the chart to a PDF document as an image. The chart control provides APIs to convert it to an image, while Syncfusion PDF lets you insert this image into a Word Document file programmatically.

Chart exported to a PDF document

  1. Add the Syncfusion.Pdf.Base and Syncfusion.Pdf.Windows assemblies.

  2. Add the namespace Syncfusion.Pdf in your form.

    using Syncfusion.Pdf;
    using Syncfusion.Pdf.Graphics;
    Imports Syncfusion.Pdf
    Imports Syncfusion.Pdf.Graphics
  3. Add the code snippet that is given below in your form.

    string fileName=Application.StartupPath+"\\chartExport";
    string exportFileName = fileName + ".pdf";
    string file = fileName + ".gif";
    this.chartControl.SaveImage(file);
    //Create a PDF document
    PdfDocument pdfDoc = new PdfDocument();
    //Add a page to the empty PDF document
    pdfDoc.Pages.Add();                   
    //Draw chart image in the first page
    pdfDoc.Pages[0].Graphics.DrawImage(PdfImage.FromFile(file), new PointF(10, 30));
    //Save the PDF Document to disk.
    pdfDoc.Save(exportFileName);
    // Launches the file.                         
    System.Diagnostics.Process.Start(exportFileName);
    Dim fileName As String = Application.StartupPath & "\chartExport"
    Dim exportFileName As String = fileName & ".pdf"
    Dim file As String = fileName & ".gif"
    Me.chartControl.SaveImage(file)
    'Create a PDF document
    Dim pdfDoc As PdfDocument = New PdfDocument()
    'Add a page to the empty PDF document
    pdfDoc.Pages.Add()
    'Draw chart image in the first page
    pdfDoc.Pages(0).Graphics.DrawImage(PdfImage.FromFile(file), New PointF(10, 30))
    'Save the PDF Document to disk.
    pdfDoc.Save(exportFileName)
    ' Launches the file.                         
    System.Diagnostics.Process.Start(exportFileName)

Exporting to CSV

Chart data can easily be exported to a CSV file by retrieving the X and Y values from the chart series and writing them in a comma separated format.

The following code example demonstrates how to export chart data to a CSV file.

string fileName = Application.StartupPath + "\\chartExport";
string csvContent = String.Empty, csvLine = String.Empty;
string comma = ",";
string exportFileName = fileName + ".csv";

foreach (ChartSeries series in this.chartControl.Series)
{
    string seriesName = series.Name;
    int pointCount = series.Points.Count;
    string seriesType = series.Type.ToString();

    for (int p = 0; p < pointCount; p++)
    {
        ChartPoint point = series.Points[p];

        string yvaluescsv = String.Empty;
        int count = point.YValues.Length;
        for (int i = 0; i < count; i++)
        {
            yvaluescsv += point.YValues[i];
            if (i != count - 1)
                yvaluescsv += comma;
        }

        //The format of the csv can be given here.
        //csvLine = seriesName + "-" + seriesType + comma + point.X + comma + yvaluescsv;

        csvLine = point.X + comma + yvaluescsv;
        csvContent += csvLine + "\n";
    }
}

//Initializes the stream to write the contents in a file.
System.IO.StreamWriter file = new System.IO.StreamWriter(exportFileName);
file.WriteLine(csvContent);
file.Close();

System.Diagnostics.Process.Start(exportFileName);
Dim fileName As String = Application.StartupPath & "\chartExport"
Dim csvContent As String = String.Empty
Dim csvLine As String = String.Empty
Dim comma As String = ","
Dim exportFileName As String = fileName & ".csv"

For Each series As ChartSeries In Me.chartControl.Series
    Dim seriesName As String = series.Name
    Dim pointCount As Integer = series.Points.Count
    Dim seriesType As String = series.Type.ToString()

    For p As Integer = 0 To pointCount - 1
        Dim point As ChartPoint = series.Points(p)

        Dim yvaluescsv As String = String.Empty
        Dim count As Integer = point.YValues.Length

        For i As Integer = 0 To count - 1
            yvaluescsv &= point.YValues(i)

            If i <> count - 1 Then
                yvaluescsv &= comma
            End If
        Next

        ' The format of the CSV can be specified here.
        ' csvLine = seriesName & "-" & seriesType & comma & point.X & comma & yvaluescsv

        csvLine = point.X & comma & yvaluescsv
        csvContent &= csvLine & Environment.NewLine
    Next
Next

' Initializes the stream to write the contents to a file.
Dim file As New System.IO.StreamWriter(exportFileName)
file.WriteLine(csvContent)
file.Close()

System.Diagnostics.Process.Start(exportFileName)

See also