Articles in this section
Category / Section

How to create clustered bar chart in the Word document using dynamic data from database using WinForms DocIO?

14 mins read

Syncfusion® DocIO is a .NET Word library used to create, read, and edit Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can create a clustered bar chart in the Word document using dynamic data from the database.

Steps to create clustered bar chart in the Word document using the dynamic data:

  1. Create a new C# console application (.NET Framework) project.
    Create .NET Framework console application in Visual Studio
  2. Install the Syncfusion.DocIO.Winforms NuGet package as a reference to your .NET Framework applications from NuGet.org.
    Add DocIO.WinForms NuGet packages
  3. Include the following namespace in the Program.cs file.

C#

using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.OfficeChart;

VB.NET

Imports Syncfusion.DocIO
Imports Syncfusion.DocIO.DLS
Imports Syncfusion.OfficeChart
  1. Use the following code example to create clustered bar chart in the Word document using the dynamic data from database.

C#

           //Creates a new WordDocument.
           using (WordDocument document = new WordDocument())
           {
               //Adds section to the document.
               IWSection sec = document.AddSection();
               //Adds paragraph to the section.
               IWParagraph paragraph = sec.AddParagraph();
               //Creates and appends chart to the paragraph.
               WChart chart = paragraph.AppendChart(470, 300);

               //Sets chart type.
               chart.ChartType = OfficeChartType.Bar_Clustered;

               //Assign data range.
               chart.DataRange = chart.ChartData[1, 1, 6, 4];
               chart.IsSeriesInRows = false;

               //Gets the data table from the database.
               DataTable dataTable = GetDataTable();
               //Sets data to the chart - RowIndex, columnIndex and data.
               SetChartData(chart, dataTable);

               //Apply chart elements.
               //Set chart title.
               chart.ChartTitle = "Clustered Bar Chart";

               //Sets Datalabels.
               IOfficeChartSerie serie1 = chart.Series[0];
               IOfficeChartSerie serie2 = chart.Series[1];
               IOfficeChartSerie serie3 = chart.Series[2];

               serie1.DataPoints.DefaultDataPoint.DataLabels.IsValue = true;
               serie2.DataPoints.DefaultDataPoint.DataLabels.IsValue = true;
               serie3.DataPoints.DefaultDataPoint.DataLabels.IsValue = true;
               serie1.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Center;
               serie2.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Center;
               serie3.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Center;

               //Sets legend.
               chart.HasLegend = true;
               chart.Legend.Position = OfficeLegendPosition.Bottom;
               //Creates file stream.
               using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"../../Result.docx"), FileMode.Create, FileAccess.ReadWrite))
               {
                   //Saves the Word document to file stream.
                   document.Save(outputFileStream, FormatType.Docx);
               }
           }

VB.NET

           'Creates a new WordDocument.
           Imports (WordDocument document = New WordDocument())
           {
               'Adds section to the document.
               Dim sec As IWSection =  document.AddSection() 
               'Adds paragraph to the section.
               Dim paragraph As IWParagraph =  sec.AddParagraph() 
               'Creates and appends chart to the paragraph.
               Dim chart As WChart =  paragraph.AppendChart(470,300) 

               'Sets chart type.
               chart.ChartType = OfficeChartType.Bar_Clustered

               'Assign data range.
               chart.DataRange = chart.ChartData(1, 1, 6, 4)
               chart.IsSeriesInRows = False

               'Gets the data table from the database.
               Dim dataTable As DataTable =  GetDataTable() 
               'Sets data to the chart - RowIndex, columnIndex and data.
               SetChartData(chart, dataTable)

               'Apply chart elements.
               'Set chart title.
               chart.ChartTitle = "Clustered Bar Chart"

               'Sets Datalabels.
               Dim serie1 As IOfficeChartSerie =  chart.Series(0) 
               Dim serie2 As IOfficeChartSerie =  chart.Series(1) 
               Dim serie3 As IOfficeChartSerie =  chart.Series(2) 

               serie1.DataPoints.DefaultDataPoInteger.DataLabels.IsValue = True
               serie2.DataPoints.DefaultDataPoInteger.DataLabels.IsValue = True
               serie3.DataPoints.DefaultDataPoInteger.DataLabels.IsValue = True
               serie1.DataPoints.DefaultDataPoInteger.DataLabels.Position = OfficeDataLabelPosition.Center
               serie2.DataPoints.DefaultDataPoInteger.DataLabels.Position = OfficeDataLabelPosition.Center
               serie3.DataPoints.DefaultDataPoInteger.DataLabels.Position = OfficeDataLabelPosition.Center

               'Sets legend.
               chart.HasLegend = True
               chart.Legend.Position = OfficeLegendPosition.Bottom
               'Creates file stream.
               Imports (FileStream outputFileStream = New FileStream(Path.GetFullPath("../../Result.docx"), FileMode.Create, FileAccess.ReadWrite))
               {
                   'Saves the Word document to file stream.
                   document.Save(outputFileStream, FormatType.Docx)
               }
           }
  1. Add the below helper methods to get the data from database.

C#

       private static DataTable GetDataTable()
       {
           string path = Path.GetFullPath(@"../../Data/DataBase.mdb");
           //Create a new instance of OleDbConnection
           OleDbConnection connection = new OleDbConnection();
           //Sets the string to open a Database
           connection.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0;Password=\"\";User ID=Admin;Data Source=" + path;
           //Opens the Database connection
           connection.Open();
           //Get all the data from the Database
           OleDbCommand query = new OleDbCommand("select * from Fruits", connection);
           //Create a new instance of OleDbDataAdapter
           OleDbDataAdapter adapter = new OleDbDataAdapter(query);
           //Create a new instance of DataSet
           DataSet dataSet = new DataSet();
           //Adds rows in the Dataset
           adapter.Fill(dataSet);
           //Create a DataTable from the Dataset
           DataTable table = dataSet.Tables[0];
           return table;
       }
       
       private static void SetChartData(WChart chart, DataTable dataTable)
       {
           //Sets the heading for chart data.
           chart.ChartData.SetValue(1, 1, "Fruits");
           chart.ChartData.SetValue(1, 2, "Joey");
           chart.ChartData.SetValue(1, 3, "Mathew");
           chart.ChartData.SetValue(1, 4, "Peter");

           int rowIndex = 2;
           int colIndex = 1;
           //Get the values from the DataTable and set the value for chart data.
           foreach (DataRow row in dataTable.Rows)
           {
               foreach (object val in row.ItemArray)
               {
                   string value = val.ToString();
                   //Sets data to the chart - RowIndex, columnIndex and data.
                   chart.ChartData.SetValue(rowIndex, colIndex, value);
                   colIndex++;
                   if (colIndex == (row.ItemArray.Length + 1))
                       break;
               }
               colIndex = 1;
               rowIndex++;
           }
       }

VB.NET

Private Shared Function GetDataTable() As DataTable
           Dim path As String =  Path.GetFullPath("../../Data/DataBase.mdb") 
           'Create a new instance of OleDbConnection
           Dim connection As OleDbConnection =  New OleDbConnection() 
           'Sets the string to open a Database
           connection.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0;Password=\"\";User ID=Admin;Data Source=" + path
           'Opens the Database connection
           connection.Open()
           'Get all the data from the Database
           Dim query As OleDbCommand =  New OleDbCommand("select * from Fruits",connection) 
           'Create a new instance of OleDbDataAdapter
           Dim adapter As OleDbDataAdapter =  New OleDbDataAdapter(query) 
           'Create a new instance of DataSet
           Dim dataSet As DataSet =  New DataSet() 
           'Adds rows in the Dataset
           adapter.Fill(dataSet)
           'Create a DataTable from the Dataset
           Dim table As DataTable =  dataSet.Tables(0) 
           Return table
End Function

Private Shared  Sub SetChartData(ByVal chart As WChart, ByVal dataTable As DataTable)
           'Sets the heading for chart data.
           chart.ChartData.SetValue(1, 1, "Fruits")
           chart.ChartData.SetValue(1, 2, "Joey")
           chart.ChartData.SetValue(1, 3, "Mathew")
           chart.ChartData.SetValue(1, 4, "Peter")

           Dim rowIndex As Integer =  2 
           Dim colIndex As Integer =  1 
           'Get the values from the DataTable and set the value for chart data.
           Dim row As DataRow
           For Each row In dataTable.Rows
               Dim val As Object
               For Each val In row.ItemArray
                   Dim value As String =  val.ToString() 
                   'Sets data to the chart - RowIndex, columnIndex and data.
                   chart.ChartData.SetValue(rowIndex, colIndex, value)
                   colIndex = colIndex + 1
                   If colIndex =(row.ItemArray.Length + 1) Then
                       Exit For
                   End If
               Next
               colIndex = 1
               rowIndex = rowIndex + 1
           Next
End Sub

A complete working sample to create clustered bar chart in the Word document using the dynamic data from database using C# can be downloaded from GitHub.

By executing the program, you will get the Word document as follows.

Output document generated

Take a moment to peruse the documentation, where you can find basic Word document processing options along with the features like mail mergemerge, and compare documentsfind and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples.

Explore more about the rich set of Syncfusion® Word Framework features.

Conclusion

I hope you enjoyed learning about How to create clustered bar chart in the Word document using dynamic data from database using WinForms DocIO.

You can refer to our WinForms DocIO feature tour page to know about its other groundbreaking feature representations. You can also explore our WinForms DocIO documentation to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

See Also

  1. How to set Date format in X axis of chart in Word document

  2. How to change scatter chart marker color for each data points in Word document

  3. How to create line chart in Word document using C# and VB.NET

  4. How to create clustered column chart in Word document using C# and VB.NET

  5. How to create bubble chart in Word document using C# and VB.NET

  6. How to create line chart with different color series in Word document using C#?

  7. How to set column space for column charts in Word document?

  8. How to set Y-axis interval for column charts in Word document?

  9. How to change chart title position in the Word document?

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied