DEV Community

Allen Yang
Allen Yang

Posted on

How to Generate and Customize Word Charts Using C#

Create Charts in Word Documents with C#

Generating reports and visualizing data are crucial tasks in many business applications. While Microsoft Word is a ubiquitous tool for document creation, manually embedding and updating charts can be a tedious and error-prone process. This tutorial addresses the challenge of automating report generation and dynamic data visualization by demonstrating how to programmatically create and customize charts within Word documents using C#. By leveraging the power of a robust .NET library, developers can achieve significant efficiency and maintain high accuracy in their document workflows.


Setting Up Your Environment

To begin creating charts in Word documents programmatically with C#, you'll need a powerful library that can interact with Word files without requiring Microsoft Office to be installed. For this tutorial, we will be using Spire.Doc for .NET. This library provides comprehensive functionalities for Word document manipulation, including chart creation.

Installation via NuGet

The easiest way to integrate Spire.Doc for .NET into your C# project is through NuGet Package Manager.

Create a New Project: Open Visual Studio and create a new C# Console Application (.NET Core or .NET Framework, depending on your preference).

Install the NuGet Package:

  • Right-click on your project in the Solution Explorer.
  • Select "Manage NuGet Packages...".
  • In the "Browse" tab, search for Spire.Doc.
  • Select Spire.Doc from the search results and click "Install".

Once installed, you'll have access to all the necessary classes and methods for working with Word documents and charts.


Understanding Chart Types and Data Series

Before diving into code, it's essential to understand the fundamental components of a chart: chart types and data series. Spire.Doc for .NET supports a wide array of chart types commonly found in Microsoft Word, making it versatile for various data visualization needs.

Common Chart Types

The choice of chart type depends on the data you want to represent and the insights you aim to convey. Here are a few examples of supported types:

  • Bar/Column Charts: Ideal for comparing values across different categories.
  • Line Charts: Best for showing trends over time or ordered categories.
  • Pie Charts: Used to display proportions of a whole.
  • Bubble Charts: Useful for visualizing three dimensions of data (X, Y, and size).

Spire.Doc for .NET enumerates these types within the Spire.Doc.Fields.Shapes.Charts.ChartType enumeration.

Data Series

A data series is a group of related data points that are plotted in a chart. Each series typically corresponds to a specific category or measurement. For example, in a bar chart showing sales by region, each region's sales figures would constitute a data series. For a pie chart, a single series usually represents the different segments of the pie.

When preparing data for charts, you'll often work with arrays or collections of values. For many chart types, you'll need:

  • Categories (Labels): Textual descriptions for each data point (e.g., product names, months).
  • Values: Numerical data corresponding to each category.
  • Additional Values (for certain chart types): Such as bubble sizes for bubble charts.

The ChartSeriesCollection and ChartSeries classes within Spire.Doc for .NET are used to manage and add data series to your charts.


Step-by-Step Chart Creation

Let's walk through the process of creating a chart in a Word document using C# and Spire.Doc for .NET. We'll focus on creating a simple pie chart, as it clearly demonstrates the core concepts.

1. Initialize Document and Section

First, create a new Word document and add a section to it.

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Fields.Shapes.Charts; // Important for Chart and ChartSeries

// Create a new Word document
Document doc = new Document();
Section section = doc.AddSection();
Paragraph paragraph = section.AddParagraph();
Enter fullscreen mode Exit fullscreen mode

2. Append the Chart Shape

To insert a chart, you append a ShapeObject of type Chart to a paragraph. You'll specify the chart type, width, and height.

// Append a pie chart (width 500.0f, height 300.0f)
ShapeObject shape = paragraph.AppendChart(ChartType.Pie, 500.0f, 300.0f);
Chart chart = shape.Chart; // Get the Chart object from the ShapeObject
Enter fullscreen mode Exit fullscreen mode

Note: Ensure you use the full namespace Spire.Doc.Fields.Shapes.Charts.Chart if you encounter ambiguity with other Spire components.

3. Add Data Series

Now, define your categories and data values, then add them as a series to the chart. For a pie chart, a single series is typically sufficient, where each value represents a slice.

// Clear any existing series (good practice for new charts)
chart.Series.Clear();

// Define categories and data values for the pie chart
string[] categories = new[] { "Word", "PDF", "Excel" };
double[] dataValues = new[] { 2.7, 3.2, 0.8 };

// Add a series to the chart with categories (labels) and corresponding data values
ChartSeries series = chart.Series.Add("Document Types", categories, dataValues);
Enter fullscreen mode Exit fullscreen mode

Example: Bubble Chart Creation

For a more complex chart like a bubble chart, you would provide three arrays for X-values, Y-values, and bubble sizes.

Paragraph newPara = section.AddParagraph();
// Append a bubble chart shape to the paragraph with specified width and height
ShapeObject bubbleShape = newPara.AppendChart(ChartType.Bubble, 500, 300);
Chart bubbleChart = bubbleShape.Chart;

bubbleChart.Series.Clear();

// Add a new series to the chart with data points for X, Y, and bubble size values
ChartSeries bubbleSeries = bubbleChart.Series.Add("Market Share",
    new[] { 2.9, 3.5, 1.1, 4.0, 4.0 }, // X-values
    new[] { 1.9, 8.5, 2.1, 6.0, 1.5 }, // Y-values
    new[] { 9.0, 4.5, 2.5, 8.0, 5.0 }); // Bubble sizes
Enter fullscreen mode Exit fullscreen mode

4. Save the Document

Finally, save the document to see your newly created chart.

doc.SaveToFile("ChartInWordDocument.docx", FileFormat.Docx);
Enter fullscreen mode Exit fullscreen mode

The Generated Word Document

Create a Pie Chart and a Bubble Chart in a Word Document Using C#


Advanced Customization

Spire.Doc for .NET offers extensive options for customizing the appearance and behavior of your charts. This allows you to tailor charts to specific reporting requirements and enhance their readability.

Chart Title

A clear chart title is essential for understanding the chart's purpose.

void AppendChartTitle(Chart chart)
{
    ChartTitle title = chart.Title;
    title.Show = true;
    title.Overlay = false; // Set to true if title should overlap the plot area
    title.Text = "Quarterly Software Usage";
    title.CharacterFormat.FontSize = 12;
    title.CharacterFormat.Bold = true;
    title.CharacterFormat.TextColor = System.Drawing.Color.Blue;
    title.CharacterFormat.FontName = "Arial";
    // Further styling options like underline, shadow, etc. are available
}
// Call this function after creating the chart
// AppendChartTitle(chart);
Enter fullscreen mode Exit fullscreen mode

Chart Legend

Legends help identify different data series in the chart.

void AppendChartLegend(Chart chart)
{
    chart.Legend.Show = true;
    chart.Legend.Position = LegendPosition.Right; // Options: Left, Right, Top, Bottom, Corner
    chart.Legend.Overlay = false;
    chart.Legend.CharacterFormat.FontSize = 9;
    chart.Legend.CharacterFormat.TextColor = System.Drawing.Color.DarkGreen;
    chart.Legend.CharacterFormat.Italic = true;
}
// Call this function after creating the chart
// AppendChartLegend(chart);
Enter fullscreen mode Exit fullscreen mode

Chart Axes (for relevant chart types)

For charts with axes (like bar or line charts), you can customize their labels, titles, tick marks, and gridlines.

void AppendChartAxis(Chart chart)
{
    // Customize X-axis (Axis 0)
    if (chart.Axes.Count > 0)
    {
        chart.Axes[0].CategoryType = AxisCategoryType.Category;
        chart.Axes[0].Title.Text = "Product Category";
        chart.Axes[0].Title.Show = true;
        chart.Axes[0].HasMajorGridlines = false;
        chart.Axes[0].Labels.Position = AxisTickLabelPosition.Low;
        chart.Axes[0].Title.GetCharacterFormat().TextColor = System.Drawing.Color.Red;
    }

    // Customize Y-axis (Axis 1)
    if (chart.Axes.Count > 1)
    {
        chart.Axes[1].Title.Text = "Sales Volume";
        chart.Axes[1].Title.Show = true;
        chart.Axes[1].HasMajorGridlines = true;
        chart.Axes[1].Labels.IsAutoSpacing = true;
        chart.Axes[1].Title.GetCharacterFormat().Bold = true;
    }
}
// Call this function after creating the chart
// AppendChartAxis(chart);
Enter fullscreen mode Exit fullscreen mode

Data Labels

Displaying data labels directly on the chart can provide quick insights.

void AppendChartDataLabel(Chart chart, ChartType chartType)
{
    if (chart.Series.Count > 0)
    {
        ChartSeries series = chart.Series[0];
        series.HasDataLabels = true;
        ChartDataLabelCollection dataLabels = series.DataLabels;

        dataLabels.ShowValue = true; // Show the actual value
        dataLabels.ShowCategoryName = true; // Show the category name
        dataLabels.ShowLegendKey = false; // Whether to show legend keys
        dataLabels.CharacterFormat.FontSize = 10;
        dataLabels.CharacterFormat.TextColor = System.Drawing.Color.Black;

        if (chartType == ChartType.Pie || chartType == ChartType.Pie3D)
        {
            dataLabels.ShowPercentage = true; // For pie charts, show percentage
        }
        else if (chartType == ChartType.Bubble || chartType == ChartType.Bubble3D)
        {
            dataLabels.ShowBubbleSize = true; // For bubble charts, show bubble size
        }
        dataLabels.Separator = "; "; // Separator between multiple label elements
    }
}
// Call this function after creating the chart
// AppendChartDataLabel(chart, ChartType.Pie);
Enter fullscreen mode Exit fullscreen mode

Data Table

You can also include a data table below the chart to show the raw numbers.

void AppendChartDataTable(Chart chart)
{
    chart.DataTable.Show = true;
    chart.DataTable.ShowLegendKeys = true;
    chart.DataTable.ShowHorizontalBorder = true;
    chart.DataTable.ShowVerticalBorder = true;
    chart.DataTable.ShowOutlineBorder = true;
}
// Call this function after creating the chart
// AppendChartDataTable(chart);
Enter fullscreen mode Exit fullscreen mode

These functions illustrate just a subset of the customization possibilities. By combining these options, you can create highly detailed and visually appealing charts that perfectly fit your reporting needs.


Conclusion

This tutorial has demonstrated a powerful and efficient method for creating and customizing charts in Word documents using C# and Spire.Doc for .NET. We've covered the essential steps from environment setup and understanding chart components to detailed, programmatic chart creation and advanced customization. The ability to generate dynamic charts directly within Word documents opens up significant opportunities for automating report generation, enhancing data visualization in business applications, and streamlining workflows. By leveraging these techniques, developers can produce high-quality, data-rich documents with precision and at scale, transforming static reports into dynamic, data-driven insights. Further exploration of Spire.Doc for .NET's extensive API will reveal even more possibilities for sophisticated document automation.

Top comments (0)