當您生成 Word 報告時,您可以格式化圖表的繪圖區域,以配合文件的其餘部分。繪圖區域是圖表顯示其資料的地方。它位於較大的圖表區域內,該區域還可以包含標題和圖例。

本教程向您展示如何在 C# 中建立柱狀圖,為其繪圖區域套用漸層填色與邊框,並將圖表儲存於 Word 文件中。

C# 函式庫 用於格式化 Word 圖表的繪圖區域

Aspose.Words for .NET 讓您在 .NET 應用程式中建立和處理 Word 文件。圖表區域填充和線條格式化 API 在 26.10 或更高版本 中可用。

使用 .NET CLI 將套件新增至您的專案:

dotnet add package Aspose.Words --version 26.10.0

您可以在評估模式下使用該庫,或請求一個免費臨時許可證,以在無評估限制的情況下評估它。

在 C# 中格式化 Word 圖表的繪圖區域

請按照以下步驟建立並格式化圖表:

  1. 建立一個 Document 和一個 DocumentBuilder。
  2. 使用 InsertChart() 插入柱狀圖,並透過返回的 shape 存取圖表。
  3. 清除預設系列,並加入您自己的類別和數值。
  4. 存取 Chart.PlotArea.Format。
  5. 套用漸層填色,並設定邊框顏色與寬度。
  6. 將文件儲存為 DOCX 檔案。

以下完整示例建立一個包含兩個系列的圖表,並格式化其繪圖區域:

using System.Drawing;
using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Drawing.Charts;

class Program
{
    static void Main()
    {
        // Create a document and insert a column chart.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
        Chart chart = shape.Chart;

// Replace the default series with sample data.
        chart.Series.Clear();
        string[] categories = { "Quarter 1", "Quarter 2" };
        chart.Series.Add("2025", categories, new double[] { 1, 2 });
        chart.Series.Add("2026", categories, new double[] { 3, 4 });

// Set the plot-area fill and border.
        ChartPlotArea plotArea = chart.PlotArea;
        plotArea.Format.Fill.OneColorGradient(
            Color.LightBlue, GradientStyle.DiagonalUp,
            GradientVariant.Variant2, 1);
        plotArea.Format.Stroke.ForeColor = Color.Blue;
        plotArea.Format.Stroke.Weight = 0.25;

// Save the document.
        doc.Save("formatted-chart-csharp.docx");
    }
}

圖表區域格式化的工作原理

新插入的圖表包含生成的資料。範例會清除其系列,並為相同的兩個類別新增兩個具有值的系列。

Chart.PlotArea.Format 屬性提供對圖表繪圖區填充和線條格式的存取。OneColorGradient() 設定漸層顏色、樣式、變體和度數。Stroke.ForeColor 設定邊框顏色,而 Stroke.Weight 設定其寬度;範例使用 0.25 點。

查看已格式化的圖表

在 Word 文檔檢視器中打開 formatted-chart-csharp.docx。該文檔包含一個帶有兩個資料系列的柱狀圖,圖表區域具有淡藍色漸層,且有細藍色邊框。將資料和格式設定值更改為符合您的報告。

格式化 Word 圖表的繪圖區域。

格式化 Word 圖表的繪圖區域。

結論

您已使用 C# 創建了 Word 柱狀圖並自訂了繪圖區域。嘗試在自己的報告中使用不同的顏色和資料,並查看 如何使用 C# 在 Word 中創建圖表 以獲得更多圖表範例。

另請參閱