Come trasformare le risposte API in report Excel in C#
Nel mondo odierno guidato dai dati, le aziende si affidano fortemente alle API REST per lo scambio di dati. Tuttavia, molti stakeholder preferiscono consumare questi dati in formato Excel per analisi e reportistica. Questa guida dimostra come costruire un’applicazione C# completa che:
- Si connette alle API REST
- Recupera i dati di risposta JSON
- Converte i dati in report Excel formattati professionalmente
- Aggiunge visualizzazioni con grafici e tabelle
Valore Aziendale
Questa soluzione offre un valore significativo attraverso:
- Automazione dei processi di estrazione manuale dei dati e creazione di report
- Garanzia dell’accuratezza dei dati eliminando la copia manuale
- Fornitura di formattazione coerente dei report
- Abilitazione della generazione programmata dei report
Guida all’Implementazione Passo-Passo
Passo 1: Crea una Nuova Applicazione C#
Inizia creando una nuova applicazione console:
dotnet new console -n ApiToExcelReporter
cd ApiToExcelReporter
Passo 2: Installa i Pacchetti Necessari
Aggiungi i pacchetti NuGet necessari:
dotnet add package Aspose.Cells
dotnet add package Newtonsoft.Json
dotnet add package RestSharp
Passo 3: Implementa il Client API REST
Crea un servizio per la comunicazione 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);
// Aggiungi autenticazione se necessario
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($"Chiamata API fallita: {response.ErrorMessage}");
}
}
Passo 4: Elabora i Dati di Risposta JSON
Aggiungi una classe per elaborare i dati 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);
// Gestisci diverse strutture JSON
if (token is JArray array)
{
foreach (var item in array)
{
results.Add(FlattenObject(item));
}
}
else if (token is JObject obj)
{
// Per dati annidati come {"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;
}
}
}
Passo 5: Converte in Excel con Aspose.Cells
Implementa la conversione in 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)
{
// Crea un nuovo workbook
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
// Configura le opzioni di layout JSON
JsonLayoutOptions options = new JsonLayoutOptions
{
ArrayAsTable = true,
ConvertNumericOrDate = true,
IgnoreNull = true
};
// Rendi i titoli in grassetto
options.TitleStyle = new CellsFactory().CreateStyle();
options.TitleStyle.Font.IsBold = true;
// Importa i dati JSON
JsonUtility.ImportData(jsonData, sheet.Cells, 0, 0, options);
// Adatta automaticamente le colonne
sheet.AutoFitColumns();
// Salva il workbook
workbook.Save(outputPath);
}
public void GenerateReportFromObjects(List<Dictionary<string, object>> data, string outputPath)
{
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
// Aggiungi intestazioni se ci sono dati
if (data.Count > 0)
{
int col = 0;
foreach (var key in data[0].Keys)
{
// Aggiungi intestazione con stile
Cell cell = sheet.Cells[0, col];
cell.PutValue(key);
Style style = cell.GetStyle();
style.Font.IsBold = true;
cell.SetStyle(style);
col++;
}
// Aggiungi righe di dati
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++;
}
}
}
// Formatta come tabella
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");
}
// Adatta automaticamente le colonne
sheet.AutoFitColumns();
// Salva il workbook
workbook.Save(outputPath);
}
}
Passo 6: Aggiungi Formattazione Professionale
Migliora l’output Excel con uno stile professionale:
public void ApplyProfessionalFormatting(Workbook workbook)
{
Worksheet sheet = workbook.Worksheets[0];
// Crea uno stile per il titolo
Style titleStyle = workbook.CreateStyle();
titleStyle.Font.Size = 14;
titleStyle.Font.IsBold = true;
titleStyle.HorizontalAlignment = TextAlignmentType.Center;
// Aggiungi un titolo al report
sheet.Cells.Merge(0, 0, 1, sheet.Cells.MaxColumn + 1);
Cell titleCell = sheet.Cells[0, 0];
titleCell.PutValue("Report Dati API - " + DateTime.Now.ToString("yyyy-MM-dd"));
titleCell.SetStyle(titleStyle);
// Inserisci una riga vuota dopo il titolo
sheet.Cells.InsertRow(1);
// Applica colori alternati alle righe dei dati
Style evenRowStyle = workbook.CreateStyle();
evenRowStyle.ForegroundColor = Color.FromArgb(240, 240, 240);
evenRowStyle.Pattern = BackgroundType.Solid;
int dataStartRow = 3; // Tenendo conto del titolo e della riga vuota
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);
}
}
// Aggiungi intestazione e piè di pagina
sheet.PageSetup.SetHeader(1, "&\"Arial,Bold\"&14Report API");
sheet.PageSetup.SetFooter(1, "Pagina &P di &N");
// Imposta le opzioni di stampa
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;
}
Passo 7: Aggiungi Visualizzazione dei Dati
Migliora il report con grafici:
public void AddChartVisualization(Workbook workbook, int dataColumn)
{
Worksheet sheet = workbook.Worksheets[0];
Worksheet chartSheet = workbook.Worksheets.Add("Analisi Grafico");
// Ottieni l'intervallo di dati (salta la riga di intestazione)
int lastRow = sheet.Cells.MaxRow;
int nameColumn = 0; // Supponendo che la prima colonna contenga nomi/categorie
// Aggiungi un grafico
int chartIndex = chartSheet.Charts.Add(ChartType.Column, 2, 2, 20, 10);
Chart chart = chartSheet.Charts[chartIndex];
// Imposta l'intervallo di dati per il grafico
chart.NSeries.Add($"Sheet1!B2:B{lastRow + 1}", true);
chart.NSeries.CategoryData = $"Sheet1!A2:A{lastRow + 1}";
// Imposta il titolo del grafico e altre proprietà
chart.Title.Text = "Analisi Dati";
chart.Legend.Position = LegendPositionType.Bottom;
// Ulteriore personalizzazione del grafico
chart.NSeries[0].Area.ForegroundColor = Color.FromArgb(79, 129, 189);
chart.PlotArea.Area.ForegroundColor = Color.White;
// Aggiungi etichette dei dati
chart.NSeries[0].DataLabels.IsValueShown = true;
chart.NSeries[0].DataLabels.Position = DataLabelPositionType.OutsideEnd;
}
Passo 8: Metti Tutto Insieme
Crea il programma principale che unisce tutto:
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
try
{
// Configura l'endpoint API
string baseUrl = "https://api.example.com";
string endpoint = "/data/endpoint";
string apiKey = "your-api-key"; // Se necessario
// Connettiti all'API e ottieni i dati
Console.WriteLine("Connessione all'API...");
var apiService = new ApiService(baseUrl);
var jsonData = await apiService.GetApiDataAsync<string>(endpoint, apiKey);
Console.WriteLine("Dati recuperati con successo");
// Genera il report Excel
Console.WriteLine("Generazione del report Excel...");
var reportGenerator = new ExcelReportGenerator();
// Opzione 1: Conversione diretta da JSON a Excel
string outputPath = "ApiReport_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xlsx";
reportGenerator.GenerateReport(jsonData, outputPath);
// Opzione 2: Elabora JSON e crea un report migliorato
// var processor = new DataProcessor();
// var processedData = processor.FlattenJsonData(jsonData);
// reportGenerator.GenerateReportFromObjects(processedData, outputPath);
Console.WriteLine($"Report salvato in {outputPath}");
}
catch (Exception ex)
{
Console.WriteLine($"Errore: {ex.Message}");
}
}
}
Gestire Diverse Strutture di Risposta API
Le API REST restituiscono dati in vari formati. Ecco come gestire le strutture comuni:
1. Array di Oggetti
[
{ "id": 1, "name": "Prodotto A", "price": 29.99 },
{ "id": 2, "name": "Prodotto B", "price": 49.99 }
]
Per questa struttura, utilizza:
JsonLayoutOptions options = new JsonLayoutOptions();
options.ArrayAsTable = true;
JsonUtility.ImportData(jsonData, sheet.Cells, 0, 0, options);
2. Oggetto Annidato con Array di Dati
{
"status": "success",
"data": [
{ "id": 1, "name": "Prodotto A", "price": 29.99 },
{ "id": 2, "name": "Prodotto B", "price": 49.99 }
]
}
Utilizza la classe DataProcessor per estrarre l’array “data”, oppure:
// Analizza con Newtonsoft.Json
JObject jsonObj = JObject.Parse(jsonData);
JArray dataArray = (JArray)jsonObj["data"];
// Converti in stringa e importa
string dataArrayJson = dataArray.ToString();
JsonUtility.ImportData(dataArrayJson, sheet.Cells, 0, 0, options);
3. Array e Oggetti Annidati
{
"categories": [
{
"name": "Elettronica",
"products": [
{ "id": 1, "name": "Laptop", "price": 999.99 },
{ "id": 2, "name": "Telefono", "price": 699.99 }
]
},
{
"name": "Libri",
"products": [
{ "id": 3, "name": "Romanzo", "price": 14.99 }
]
}
]
}
Per strutture complesse, crea più fogli di lavoro:
// Analizza il JSON
JObject root = JObject.Parse(jsonData);
JArray categories = (JArray)root["categories"];
// Crea un foglio di lavoro per ogni categoria
foreach (var category in categories)
{
string categoryName = category["name"].ToString();
Worksheet sheet = workbook.Worksheets.Add(categoryName);
// Ottieni e importa l'array dei prodotti
JArray products = (JArray)category["products"];
JsonUtility.ImportData(products.ToString(), sheet.Cells, 0, 0, options);
}
Portare al Livello Successivo: Report Programmati
Per automatizzare la generazione dei report, aggiungi funzionalità di pianificazione:
// Installa il pacchetto Task Scheduler
// dotnet add package TaskScheduler
using Microsoft.Win32.TaskScheduler;
public void ScheduleDailyReportGeneration(string appPath)
{
using (TaskService ts = new TaskService())
{
// Crea un nuovo task
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Generazione Report Dati API Giornaliera";
// Crea un trigger che si attiverà giornalmente alle 7 del mattino
td.Triggers.Add(new DailyTrigger { StartBoundary = DateTime.Today.AddHours(7) });
// Crea un'azione che eseguirà l'applicazione
td.Actions.Add(new ExecAction(appPath));
// Registra il task nella cartella radice
ts.RootFolder.RegisterTaskDefinition("DailyApiReport", td);
}
}
Funzionalità Avanzate da Considerare
- Invio email - Invia automaticamente report via email
- Integrazione multi-API - Combina dati da più API
- Report basati su template - Utilizza template Excel per un branding coerente
- Creazione di dashboard - Genera dashboard interattive in Excel
- Tracciamento e reporting degli errori - Registra problemi e riporta su successo/fallimento
Seguendo questa guida, hai creato un’applicazione C# robusta che automatizza il processo di recupero dei dati API e la loro conversione in report Excel professionali, risparmiando tempo, garantendo accuratezza e offrendo valore aziendale.