چگونه پاسخ‌های API را به گزارش‌های Excel در C# تبدیل کنیم

چگونه پاسخ‌های API را به گزارش‌های Excel در C# تبدیل کنیم

در دنیای امروز که داده‌محور است، کسب‌وکارها به شدت به REST APIs برای تبادل داده متکی هستند. با این حال، بسیاری از ذینفعان ترجیح می‌دهند این داده‌ها را به فرمت Excel برای تحلیل و گزارش‌گیری مصرف کنند. این راهنما نشان می‌دهد چگونه یک برنامه کامل C# را بسازیم که:

  1. به REST APIs متصل می‌شود
  2. دریافت می‌کند JSON داده‌های پاسخ
  3. داده‌ها را به گزارش‌های Excel با قالب‌بندی حرفه‌ای تبدیل می‌کند
  4. تصویری‌سازی با نمودارها و جداول را اضافه می‌کند

ارزش تجاری

این راه‌حل ارزش قابل‌توجهی ارائه می‌دهد از طریق:

  • خودکارسازی فرآیندهای استخراج داده‌های دستی و ایجاد گزارش
  • اطمینان از دقت داده‌ها با حذف کپی‌برداری دستی
  • ارائه قالب‌بندی گزارش سازگار
  • فعال‌سازی تولید گزارش زمان‌بندی‌شده

راهنمای گام‌به‌گام پیاده‌سازی

مرحله 1: ایجاد یک برنامه C# جدید

با ایجاد یک برنامه کنسولی جدید شروع کنید:

dotnet new console -n ApiToExcelReporter
cd ApiToExcelReporter

مرحله 2: نصب بسته‌های مورد نیاز

بسته‌های لازم NuGet را اضافه کنید:

dotnet add package Aspose.Cells
dotnet add package Newtonsoft.Json
dotnet add package RestSharp

مرحله 3: پیاده‌سازی کلاینت REST API

یک سرویس برای ارتباط با API ایجاد کنید:

using RestSharp;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;

public class ApiService
{
    private readonly RestClient _client;
    
    public ApiService(string baseUrl)
    {
        _client = new RestClient(baseUrl);
    }
    
    public async Task<T> GetApiDataAsync<T>(string endpoint, string apiKey = null)
    {
        var request = new RestRequest(endpoint, Method.Get);
        
        // Add authentication if needed
        if (!string.IsNullOrEmpty(apiKey))
        {
            request.AddHeader("Authorization", $"Bearer {apiKey}");
        }
        
        var response = await _client.ExecuteAsync(request);
        
        if (response.IsSuccessful)
        {
            return JsonConvert.DeserializeObject<T>(response.Content);
        }
        
        throw new Exception($"API call failed: {response.ErrorMessage}");
    }
}

مرحله 4: پردازش داده‌های پاسخ JSON

یک کلاس برای پردازش داده‌های JSON اضافه کنید:

using Newtonsoft.Json.Linq;
using System.Collections.Generic;

public class DataProcessor
{
    public List<Dictionary<string, object>> FlattenJsonData(string jsonData)
    {
        var results = new List<Dictionary<string, object>>();
        JToken token = JToken.Parse(jsonData);
        
        // Handle different JSON structures
        if (token is JArray array)
        {
            foreach (var item in array)
            {
                results.Add(FlattenObject(item));
            }
        }
        else if (token is JObject obj)
        {
            // For nested data like {"data": [{...}, {...}]}
            var dataToken = obj["data"] as JArray;
            if (dataToken != null)
            {
                foreach (var item in dataToken)
                {
                    results.Add(FlattenObject(item));
                }
            }
            else
            {
                results.Add(FlattenObject(obj));
            }
        }
        
        return results;
    }
    
    private Dictionary<string, object> FlattenObject(JToken token)
    {
        var result = new Dictionary<string, object>();
        FillDictionary(result, token, "");
        return result;
    }
    
    private void FillDictionary(Dictionary<string, object> dict, JToken token, string prefix)
    {
        switch (token.Type)
        {
            case JTokenType.Object:
                foreach (var prop in token.Children<JProperty>())
                {
                    FillDictionary(dict, prop.Value, 
                        string.IsNullOrEmpty(prefix) ? prop.Name : $"{prefix}.{prop.Name}");
                }
                break;
                
            case JTokenType.Array:
                int index = 0;
                foreach (var item in token.Children())
                {
                    FillDictionary(dict, item, $"{prefix}[{index}]");
                    index++;
                }
                break;
                
            default:
                dict[prefix] = ((JValue)token).Value;
                break;
        }
    }
}

مرحله 5: تبدیل به Excel با Aspose.Cells

پیاده‌سازی تبدیل Excel:

using Aspose.Cells;
using Aspose.Cells.Utility;
using System;
using System.Collections.Generic;
using System.IO;

public class ExcelReportGenerator
{
    public void GenerateReport(string jsonData, string outputPath)
    {
        // Create a new workbook
        Workbook workbook = new Workbook();
        Worksheet sheet = workbook.Worksheets[0];
        
        // Configure JSON layout options
        JsonLayoutOptions options = new JsonLayoutOptions
        {
            ArrayAsTable = true,
            ConvertNumericOrDate = true,
            IgnoreNull = true
        };
        
        // Make headers bold
        options.TitleStyle = new CellsFactory().CreateStyle();
        options.TitleStyle.Font.IsBold = true;
        
        // Import JSON data
        JsonUtility.ImportData(jsonData, sheet.Cells, 0, 0, options);
        
        // Auto-fit columns
        sheet.AutoFitColumns();
        
        // Save the workbook
        workbook.Save(outputPath);
    }
    
    public void GenerateReportFromObjects(List<Dictionary<string, object>> data, string outputPath)
    {
        Workbook workbook = new Workbook();
        Worksheet sheet = workbook.Worksheets[0];
        
        // Add headers if there's data
        if (data.Count > 0)
        {
            int col = 0;
            foreach (var key in data[0].Keys)
            {
                // Add header with styling
                Cell cell = sheet.Cells[0, col];
                cell.PutValue(key);
                
                Style style = cell.GetStyle();
                style.Font.IsBold = true;
                cell.SetStyle(style);
                
                col++;
            }
            
            // Add data rows
            for (int row = 0; row < data.Count; row++)
            {
                col = 0;
                foreach (var value in data[row].Values)
                {
                    sheet.Cells[row + 1, col].PutValue(value);
                    col++;
                }
            }
        }
        
        // Format as a table
        if (data.Count > 0)
        {
            int lastRow = data.Count;
            int lastCol = data[0].Count - 1;
            
            var tableRange = sheet.Cells.CreateRange(0, 0, lastRow + 1, lastCol + 1);
            sheet.ListObjects.Add(tableRange, "DataTable");
        }
        
        // Auto-fit columns
        sheet.AutoFitColumns();
        
        // Save the workbook
        workbook.Save(outputPath);
    }
}

مرحله 6: افزودن قالب‌بندی حرفه‌ای

خروجی Excel را با استایل حرفه‌ای بهبود دهید:

public void ApplyProfessionalFormatting(Workbook workbook)
{
    Worksheet sheet = workbook.Worksheets[0];
    
    // Create a style for the title
    Style titleStyle = workbook.CreateStyle();
    titleStyle.Font.Size = 14;
    titleStyle.Font.IsBold = true;
    titleStyle.HorizontalAlignment = TextAlignmentType.Center;
    
    // Add a title to the report
    sheet.Cells.Merge(0, 0, 1, sheet.Cells.MaxColumn + 1);
    Cell titleCell = sheet.Cells[0, 0];
    titleCell.PutValue("API Data Report - " + DateTime.Now.ToString("yyyy-MM-dd"));
    titleCell.SetStyle(titleStyle);
    
    // Insert a blank row after the title
    sheet.Cells.InsertRow(1);
    
    // Apply alternating row colors to the data
    Style evenRowStyle = workbook.CreateStyle();
    evenRowStyle.ForegroundColor = Color.FromArgb(240, 240, 240);
    evenRowStyle.Pattern = BackgroundType.Solid;
    
    int dataStartRow = 3; // Accounting for title and blank row
    int lastRow = sheet.Cells.MaxRow;
    
    for (int row = dataStartRow; row <= lastRow; row += 2)
    {
        for (int col = 0; col <= sheet.Cells.MaxColumn; col++)
        {
            sheet.Cells[row, col].SetStyle(evenRowStyle);
        }
    }
    
    // Add page header and footer
    sheet.PageSetup.SetHeader(1, "&\"Arial,Bold\"&14API Report");
    sheet.PageSetup.SetFooter(1, "Page &P of &N");
    
    // Set print options
    sheet.PageSetup.Orientation = PageOrientationType.Landscape;
    sheet.PageSetup.FitToPagesWide = 1;
    sheet.PageSetup.TopMargin = 0.5;
    sheet.PageSetup.LeftMargin = 0.5;
    sheet.PageSetup.RightMargin = 0.5;
    sheet.PageSetup.BottomMargin = 0.5;
}

مرحله 7: افزودن تجسم داده‌ها

گزارش را با نمودارها بهبود دهید:

public void AddChartVisualization(Workbook workbook, int dataColumn)
{
    Worksheet sheet = workbook.Worksheets[0];
    Worksheet chartSheet = workbook.Worksheets.Add("Chart Analysis");
    
    // Get the data range (skip header row)
    int lastRow = sheet.Cells.MaxRow;
    int nameColumn = 0; // Assuming first column has names/categories
    
    // Add a chart
    int chartIndex = chartSheet.Charts.Add(ChartType.Column, 2, 2, 20, 10);
    Chart chart = chartSheet.Charts[chartIndex];
    
    // Set the data range for the chart
    chart.NSeries.Add($"Sheet1!B2:B{lastRow + 1}", true);
    chart.NSeries.CategoryData = $"Sheet1!A2:A{lastRow + 1}";
    
    // Set chart title and other properties
    chart.Title.Text = "Data Analysis";
    chart.Legend.Position = LegendPositionType.Bottom;
    
    // Additional chart customization
    chart.NSeries[0].Area.ForegroundColor = Color.FromArgb(79, 129, 189);
    chart.PlotArea.Area.ForegroundColor = Color.White;
    
    // Add data labels
    chart.NSeries[0].DataLabels.IsValueShown = true;
    chart.NSeries[0].DataLabels.Position = DataLabelPositionType.OutsideEnd;
}

مرحله 8: همه چیز را با هم ترکیب کنید

برنامه اصلی را که همه چیز را به هم متصل می‌کند ایجاد کنید:

using System;
using System.Threading.Tasks;

class ApiService
{
    private readonly string _baseUrl;
    public ApiService(string baseUrl) => _baseUrl = baseUrl;
    public async Task<T> GetApiDataAsync<T>(string endpoint, string apiKey)
    {
        await Task.CompletedTask;
        return default;
    }
}

class ExcelReportGenerator
{
    public void GenerateReport(string jsonData, string outputPath) { }
    public void GenerateReportFromObjects(object data, string outputPath) { }
}

class Program
{
    static async Task Main(string[] args)
    {
        try
        {
            // Configure API endpoint
            string baseUrl = "https://api.example.com";
            string endpoint = "/data/endpoint";
            string apiKey = "your-api-key"; // If needed
            
            // Connect to API and get data
            Console.WriteLine("Connecting to API...");
            var apiService = new ApiService(baseUrl);
            var jsonData = await apiService.GetApiDataAsync<string>(endpoint, apiKey);
            
            Console.WriteLine("Data retrieved successfully");
            
            // Generate Excel report
            Console.WriteLine("Generating Excel report...");
            var reportGenerator = new ExcelReportGenerator();
            
            // Option 1: Direct JSON to Excel conversion
            string outputPath = "ApiReport_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xlsx";
            reportGenerator.GenerateReport(jsonData, outputPath);
            
            // Option 2: Process JSON and create enhanced report
            // var processor = new DataProcessor();
            // var processedData = processor.FlattenJsonData(jsonData);
            // reportGenerator.GenerateReportFromObjects(processedData, outputPath);
            
            Console.WriteLine($"Report saved to {outputPath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

مدیریت ساختارهای مختلف پاسخ API

APIهای REST داده‌ها را در قالب‌های مختلف بازمی‌گردانند. در اینجا نحوه مدیریت ساختارهای رایج آورده شده است:

1. Array of Objects

[
  { "id": 1, "name": "Product A", "price": 29.99 },
  { "id": 2, "name": "Product B", "price": 49.99 }
]

برای این ساختار، استفاده کنید:

JsonLayoutOptions options = new JsonLayoutOptions();
options.ArrayAsTable = true;
JsonUtility.ImportData(jsonData, sheet.Cells, 0, 0, options);

2. Nested Object with Data Array

{
  "status": "success",
  "data": [
    { "id": 1, "name": "Product A", "price": 29.99 },
    { "id": 2, "name": "Product B", "price": 49.99 }
  ]
}

از کلاس DataProcessor برای استخراج آرایه “data” استفاده کنید، یا:

// Parse with Newtonsoft.Json
JObject jsonObj = JObject.Parse(jsonData);
JArray dataArray = (JArray)jsonObj["data"];

// Convert to string and import
string dataArrayJson = dataArray.ToString();
JsonUtility.ImportData(dataArrayJson, sheet.Cells, 0, 0, options);

3. Nested Arrays and Objects

{
  "categories": [
    {
      "name": "Electronics",
      "products": [
        { "id": 1, "name": "Laptop", "price": 999.99 },
        { "id": 2, "name": "Phone", "price": 699.99 }
      ]
    },
    {
      "name": "Books",
      "products": [
        { "id": 3, "name": "Novel", "price": 14.99 }
      ]
    }
  ]
}

برای ساختارهای پیچیده، چندین برگه کاری ایجاد کنید:

// Parse the JSON
JObject root = JObject.Parse(jsonData);
JArray categories = (JArray)root["categories"];

// Create a worksheet for each category
foreach (var category in categories)
{
    string categoryName = category["name"].ToString();
    Worksheet sheet = workbook.Worksheets.Add(categoryName);
    
    // Get and import the products array
    JArray products = (JArray)category["products"];
    JsonUtility.ImportData(products.ToString(), sheet.Cells, 0, 0, options);
}

به سطح بعدی می‌رویم: گزارش‌های زمان‌بندی شده

برای خودکارسازی تولید گزارش، قابلیت زمان‌بندی را اضافه کنید:

// Install Task Scheduler package
// dotnet add package TaskScheduler

using Microsoft.Win32.TaskScheduler;

public void ScheduleDailyReportGeneration(string appPath)
{
    using (TaskService ts = new TaskService())
    {
        // Create a new task
        TaskDefinition td = ts.NewTask();
        td.RegistrationInfo.Description = "Daily API Data Report Generation";
        
        // Create a trigger that will fire daily at 7am
        td.Triggers.Add(new DailyTrigger { StartBoundary = DateTime.Today.AddHours(7) });
        
        // Create an action that will run the application
        td.Actions.Add(new ExecAction(appPath));
        
        // Register the task in the root folder
        ts.RootFolder.RegisterTaskDefinition("DailyApiReport", td);
    }
}

ویژگی‌های پیشرفته برای در نظر گرفتن

  1. تحویل ایمیل - به‌صورت خودکار گزارش‌ها را از طریق ایمیل ارسال کنید
  2. یکپارچه‌سازی چند-API - ترکیب داده‌ها از چندین API
  3. گزارش‌های مبتنی بر قالب - استفاده از قالب‌های Excel برای برندسازی یکسان
  4. ایجاد داشبورد - تولید داشبوردهای تعاملی Excel
  5. ردیابی و گزارش‌گیری خطاها - ثبت مشکلات و گزارش موفقیت/شکست

با دنبال کردن این راهنما، شما یک برنامه C# قوی ایجاد کرده‌اید که فرآیند بازیابی داده‌های API و تبدیل آن به گزارش‌های حرفه‌ای اکسل را خودکار می‌کند — زمان را صرفه‌جویی می‌کند، دقت را تضمین می‌کند و ارزش تجاری را ارائه می‌دهد.

 فارسی