У цій статті описано, як створити секторну діаграму в PowerPoint за допомогою C# REST API. Ви дізнаєтеся, як створити секторну діаграму в PowerPoint за допомогою C# RESTful Service за допомогою Cloud SDK на основі .NET. Усі кроки виконуються у прикладі коду разом із описовими коментарями.
Обов’язкова умова
Завантажити Aspose.Slides Cloud SDK for Dotnet to make a Pie chart
Налаштуйте проект C# із зазначеним вище SDK для роботи з секторними діаграмами на слайді презентації
Кроки для створення кругової діаграми в PowerPoint за допомогою API на основі C# .NET
- Ініціалізуйте клієнт API за допомогою ID і KEY за допомогою класу SlidesApi
- Прочитайте локальний файл презентації та завантажте його в хмарне сховище
- Створіть секторну діаграму, визначивши її положення, розмір і тип для її налаштування
- Додайте мітки до діаграми та створіть ряд точок даних для діаграми
- Додайте ряд до діаграми та додайте цю діаграму до цільового слайда завантаженої презентації за допомогою методу CreateShape()
- Завантажити презентацію в локальний файл
Ці кроки описують як створити секторну діаграму в PowerPoint за допомогою C# RESTful Service. Створіть екземпляр об’єкта діаграми, налаштуйте його властивості, додайте категорії та створіть ряд точок даних для додавання до кругової діаграми. Нарешті, додайте секторну діаграму до цільового слайда презентації та збережіть її на локальному диску.
Код для додавання секторної діаграми в PowerPoint за допомогою C# RESTful Service
using SlidesCloud.SDK; // Importing the SDK for managing presentations | |
using SlidesCloud.SDK.Model; // Importing models used for creating and manipulating presentation components | |
using System; | |
using System.IO; | |
namespace PresentationManager // Custom namespace for this program | |
{ | |
class ShapeAdder | |
{ | |
static void Main(string[] args) // Main entry point of the program | |
{ | |
// Initialize the API client with API key and secret | |
SlidesApi presentationApi = new SlidesApi("Client ID", "Secret"); | |
// Upload the presentation file to the server | |
// Reads the local presentation file and uploads it to the cloud for processing | |
var uploadResult = presentationApi.UploadFile("SampleDeck.pptx", new MemoryStream(File.ReadAllBytes("SampleDeck.pptx"))); | |
// Configure chart properties | |
// Creating a new chart object and defining its position, size, and type | |
Chart customChart = new Chart | |
{ | |
ChartType = Chart.ChartTypeEnum.Pie, // Specifies the type of chart (Pie Chart) | |
X = 150, // X-coordinate of the chart's position on the slide | |
Y = 120, // Y-coordinate of the chart's position on the slide | |
Width = 450, // Width of the chart | |
Height = 350, // Height of the chart | |
Title = new ChartTitle { Text = "Pie Chart" } // Setting the chart title | |
}; | |
// Adding categories (labels) to the chart | |
customChart.Categories = new System.Collections.Generic.List<ChartCategory> | |
{ | |
new ChartCategory { Value = "Category A" }, // First category | |
new ChartCategory { Value = "Category B" }, // Second category | |
new ChartCategory { Value = "Category C" } // Third category | |
}; | |
// Define data series and data points | |
// Creating a series of data points for the chart | |
OneValueSeries chartSeries = new OneValueSeries | |
{ | |
IsColorVaried = true, // Allows different colors for each data point | |
DataPoints = new System.Collections.Generic.List<OneValueChartDataPoint> | |
{ | |
new OneValueChartDataPoint { Value = 35 }, // Data point for Category A | |
new OneValueChartDataPoint { Value = 45 }, // Data point for Category B | |
new OneValueChartDataPoint { Value = 20 } // Data point for Category C | |
} | |
}; | |
// Adding the series to the chart | |
customChart.Series = new System.Collections.Generic.List<Series> { chartSeries }; | |
// Add the chart to the first slide of the presentation | |
Chart insertedChart = (Chart)presentationApi.CreateShape("SampleDeck.pptx", 1, customChart); | |
// Display the number of categories in the chart | |
Console.WriteLine("Number of Categories in the Chart: " + insertedChart.Categories.Count); | |
// Download the updated presentation file from the server | |
Stream updatedPresentationStream = presentationApi.DownloadFile("SampleDeck.pptx"); | |
// Save the downloaded presentation to a local file | |
// Writing the downloaded stream to a new file on disk | |
using (var fileStream = new FileStream("UpdatedDeck.pptx", FileMode.Create, FileAccess.Write)) | |
{ | |
updatedPresentationStream.CopyTo(fileStream); | |
} | |
// Notify the user that the process is complete | |
Console.WriteLine("Updated presentation saved as 'UpdatedDeck.pptx'."); | |
} | |
} | |
} |
Наведений вище код показує як створити секторну діаграму в PPT за допомогою C# .NET API. Ви можете переконатися, що ви додаєте стільки серій збору даних, скільки категорій додано на діаграмі. Також зауважте, що завантаження презентації на початку є обов’язковою, інакше ви можете отримати винятки під час виконання коду без завантаження вихідної презентації.
Ця стаття навчила нас додавати кругову діаграму в презентацію. Щоб додати гістограму, зверніться до статті Створення гістограми в PowerPoint за допомогою C# REST API.