Insérer des segments dans Excel : Guide du débutant pour les filtres interactifs
Table des matières
- Qu'est-ce qu'un segment (Slicer) dans Excel ?
- Pourquoi les segments sont-ils plus performants que les filtres traditionnels ?
- Prérequis avant d'insérer des segments
- Comment ajouter des segments dans Excel : deux méthodes
- Avancé : Créer des segments par programmation dans Excel en C#
- Comment utiliser les segments Excel une fois insérés
- Meilleures pratiques pour les segments Excel
- Foire aux questions (FAQ)

Vous en avez assez de perdre le fil de vos filtres Excel dans des menus déroulants interminables ? Il existe une meilleure solution. Les segments (slicers) transforment l'exploration fastidieuse des données en une expérience visuelle en un clic, gardant vos sélections visibles et vos tableaux de bord interactifs.
Dans ce guide, vous apprendrez exactement comment insérer des segments dans Excel, que vous travailliez avec des tableaux classiques ou des tableaux croisés dynamiques. Nous aborderons les meilleures pratiques pour créer des tableaux de bord professionnels et nous vous montrerons même comment automatiser le processus avec C#.
- Qu'est-ce qu'un segment dans Excel ?
- Pourquoi les segments sont-ils plus performants que les filtres traditionnels ?
- Prérequis avant d'insérer des segments
- Comment ajouter des segments dans Excel : deux méthodes
- Avancé : Créer des segments par programmation dans Excel en C#
- Comment utiliser les segments Excel une fois insérés
- Meilleures pratiques pour les segments Excel
- Foire aux questions (FAQ)
Qu'est-ce qu'un segment dans Excel ?
Un segment est un outil de filtrage visuel composé de boutons cliquables qui correspondent à des valeurs uniques dans une colonne de données. Au lieu de cacher vos options de filtrage dans des menus déroulants, les segments les affichent directement sur votre feuille de calcul, rendant l'état actuel de votre filtre visible en un coup d'œil.
Considérez les segments comme un panneau de contrôle intuitif pour vos données. Cliquez sur un bouton, et votre tableau, tableau croisé dynamique ou graphique se met à jour instantanément. Les boutons sélectionnés restent en surbrillance, afin que vous et tout autre utilisateur puissiez toujours voir quels filtres sont actifs.
Pourquoi les segments sont-ils plus performants que les filtres traditionnels ?
| Fonctionnalité | Filtres traditionnels | Segments |
|---|---|---|
| Visibilité | L'état du filtre est caché dans des menus déroulants | Les filtres sélectionnés sont toujours visibles |
| Facilité d'utilisation | Nécessite plusieurs clics pour naviguer dans les menus | Sélection par bouton en un clic pour un filtrage instantané |
| Sélection multiple | Peu pratique et peu intuitif | Maintenez Ctrl ou utilisez le bouton de sélection multiple |
| Sources de données multiples | Lié à un seul tableau | Peut contrôler plusieurs tableaux croisés dynamiques et graphiques |
| Adapté aux tableaux de bord | Non conçu pour les tableaux de bord | Parfait pour les tableaux de bord interactifs |
Les filtres standard vous obligent à cliquer sur une petite flèche, décocher « Sélectionner tout », parcourir une longue liste et cliquer sur OK. Dès que vous cliquez ailleurs, vos choix de filtrage disparaissent de la vue, vous laissant deviner ce qui est actuellement appliqué. L'outil de segment Excel résout complètement ce problème en faisant de chaque option de filtre un bouton clair et cliquable placé directement sur votre feuille de calcul.
Prérequis avant d'insérer des segments
Avant d'ajouter des segments dans Excel, assurez-vous que vos données répondent à ces exigences :
- Formaté en tant que tableau Excel ou tableau croisé dynamique : Les segments ne fonctionnent pas avec des plages de cellules brutes non formatées.
- Version Excel prise en charge : Les segments sont disponibles dans Excel 2013 et versions ultérieures pour Windows, et Excel 2016 et versions ultérieures pour Mac.
- Aucune ligne ou colonne vide : Les lignes ou colonnes vides dans votre jeu de données peuvent amener Excel à mal interpréter la plage de données complète.
- Données propres et structurées : Assurez-vous que chaque colonne possède un en-tête unique et descriptif ainsi qu'un formatage de données cohérent.
Pour convertir une plage en tableau, sélectionnez vos données et appuyez sur « Ctrl + T », puis cliquez sur OK.
Comment ajouter des segments dans Excel : deux méthodes
Le processus d'insertion des segments dépend de si vous travaillez avec un tableau Excel classique ou un tableau croisé dynamique. Nous aborderons les deux.
Méthode 1 : Insérer des segments dans un tableau Excel
- Cliquez n'importe où à l'intérieur de votre tableau Excel.
- Allez dans l'onglet Création de tableau sur le ruban.
- Cliquez sur le bouton Insérer un segment dans le groupe Outils.

- Dans la boîte de dialogue contextuelle, cochez les cases des colonnes que vous souhaitez utiliser comme segments (par exemple, Région, Produit, Catégorie).
- Cliquez sur OK.

Excel placera les objets de segment directement sur votre feuille de calcul. Chaque segment affiche des boutons pour tous les éléments uniques de son champ respectif. Cliquez sur n'importe quel bouton à l'intérieur d'un segment pour filtrer le tableau instantanément.

Méthode 2 : Insérer des segments dans un tableau croisé dynamique
- Cliquez sur n'importe quelle cellule à l'intérieur de votre tableau croisé dynamique.
- Accédez à l'onglet Analyse du tableau croisé dynamique (ou onglet Analyse, selon votre version).
- Cliquez sur Insérer un segment dans le groupe Filtrer.

- Dans la boîte de dialogue Insérer des segments, cochez les cases des champs par lesquels vous souhaitez filtrer (par exemple, Produit).
- Cliquez sur OK.
Les segments apparaissent sur votre feuille et mettent à jour dynamiquement les résultats du tableau croisé dynamique. Vous pouvez les déplacer, les redimensionner et les formater pour qu'ils correspondent à la mise en page de votre tableau de bord.

Avancé : Créer des segments par programmation dans Excel en C#
Bien que les méthodes manuelles soient parfaites pour des tâches ponctuelles, vous pourriez avoir besoin d'ajouter des segments à des centaines de fichiers Excel par programmation. C'est là qu'intervient Free Spire.XLS for .NET. Cette bibliothèque gratuite vous permet de créer, lire et modifier des fichiers Excel sans que Microsoft Office soit installé — et elle prend entièrement en charge l'insertion de segments dans les tableaux Excel.
Code C# : Ajouter des segments à un tableau Excel
Voici un exemple C# complet qui charge un fichier Excel existant, récupère le premier tableau de la première feuille de calcul et insère deux segments pour deux colonnes différentes. Il définit ensuite un nom et un style intégré pour chaque segment, puis enregistre le résultat sous forme de nouveau fichier .xlsx.
using Spire.Xls;
using Spire.Xls.Core;
namespace AddSlicerToTable
{
internal class Program
{
static void Main(string[] args)
{
// Charger un fichier Excel
Workbook workbook = new Workbook();
workbook.LoadFromFile("sampleData.xlsx");
// Obtenir la première feuille de calcul
Worksheet worksheet = workbook.Worksheets[0];
// Obtenir le premier tableau de la feuille de calcul
IListObject table = worksheet.ListObjects[0];
// Ajouter 2 segments
// Paramètres : tableau, emplacement (référence de cellule), index de colonne (basé sur 0)
int slicer1 = worksheet.Slicers.Add(table, "G3", 1);
int slicer2 = worksheet.Slicers.Add(table, "H5", 2);
// Définir le nom et le style du segment
worksheet.Slicers[slicer1].Name = "Région";
worksheet.Slicers[slicer1].StyleType = SlicerStyleType.SlicerStyleLight1;
worksheet.Slicers[slicer2].Name = "Catégorie";
worksheet.Slicers[slicer2].StyleType = SlicerStyleType.SlicerStyleDark1;
// Enregistrer le fichier de résultat
workbook.SaveToFile("AddSlicers.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}
Comment fonctionne l'API de segment
La méthode principale est Slicers.Add() avec la signature suivante :
int Add(IListObject table, string destCellName, int index);
- table : L'objet IListObject source (Tableau Excel) auquel le segment est lié
- destCellName : Adresse de la cellule en haut à gauche où le segment est placé (par exemple, "G3")
- index : Index basé sur 0 de la colonne dans le tableau à utiliser comme valeurs de filtre.
Remarque : Les segments nécessitent un objet Tableau Excel structuré. Créez et configurez toujours votre tableau Excel avant d'appeler l'API d'insertion de segment.
Résultat :

Conseils supplémentaires pour l'insertion programmatique de segments
- Tableaux multiples : Si votre feuille de calcul contient plus d'un tableau, vous pouvez y accéder via worksheet.ListObjects[index].
- Segments de tableau croisé dynamique : Free Spire.XLS prend également en charge l'ajout de segments aux tableaux croisés dynamiques en utilisant
worksheet.Slicers.Add(IPivotTable, string, int). - Formats d'enregistrement : Utilisez
ExcelVersion.Version2013ouVersion2016pour vous assurer que les segments sont correctement conservés. - Performance : Lors du traitement de plusieurs fichiers, créez une nouvelle instance de Workbook pour chaque fichier et appelez Dispose() rapidement après le traitement pour éviter les fuites de mémoire.
Comment utiliser les segments Excel une fois insérés
L'utilisation des segments est remarquablement simple :
- Sélection unique : Cliquez sur n'importe quel bouton pour filtrer vos données sur cette valeur
- Sélection multiple : Maintenez Ctrl tout en cliquant sur plusieurs boutons, ou cliquez sur le bouton Sélection multiple en haut du panneau de segment
- Effacer un filtre : Cliquez sur le bouton Effacer le filtre (l'icône d'entonnoir avec un X) dans le coin supérieur droit du segment

Meilleures pratiques pour les segments Excel
- Gardez les segments regroupés et alignés en haut ou sur le côté de votre tableau de bord.
- Utilisez des légendes descriptives pour que les utilisateurs comprennent ce que chaque segment filtre.
- Limitez le nombre de segments — 3 à 5 offrent généralement suffisamment d'interactivité sans encombrer.
- Nommez vos segments dans le volet de sélection (Alt + F10) pour une gestion plus facile.
- Verrouillez les positions des segments (clic droit → Taille et propriétés → Propriétés → cochez « Ne pas déplacer ou dimensionner avec les cellules ») afin qu'ils restent en place lorsque les utilisateurs font défiler.
- Pour l'automatisation, ciblez toujours ExcelVersion.Version2016 ou supérieure pour garantir la compatibilité des segments.
Réflexions finales
L'ajout de segments dans Excel est l'une des compétences les plus percutantes pour quiconque crée des rapports ou des tableaux de bord. Pour les utilisateurs quotidiens, ils rendent le filtrage intuitif, transparent et prêt pour les tableaux de bord, éliminant la friction des menus déroulants imbriqués. Pour les développeurs, les API de segment programmatiques permettent une génération évolutive et automatisée de classeurs interactifs à l'échelle de l'entreprise.
Ne vous contentez pas de feuilles de calcul statiques qui déroutent votre public. Commencez à utiliser les segments Excel dès aujourd'hui pour libérer tout le potentiel de vos données — transformant des tableaux ordinaires en outils de prise de décision puissants et interactifs qui impressionnent et informent.
Foire aux questions (FAQ)
Q : Puis-je connecter un segment à plusieurs tableaux croisés dynamiques ?
R : Oui. Faites un clic droit sur le segment → Connexions de rapport → sélectionnez tous les tableaux croisés dynamiques que vous souhaitez contrôler.
Q : Puis-je changer les couleurs des segments ?
R : Absolument. Utilisez l'onglet Outils de segment → Options pour appliquer des styles intégrés ou créer un formatage personnalisé.
Q : Les segments fonctionnent-ils avec les graphiques Excel ?
R : Oui. Si un graphique est lié à un tableau ou un tableau croisé dynamique qui possède un segment associé, le graphique se mettra à jour automatiquement pour refléter vos sélections de segment.
Q : Puis-je modifier l'ordre de tri des éléments à l'intérieur d'un segment ?
R : Oui. Faites un clic droit sur le segment et sélectionnez Paramètres du segment. Dans la boîte de dialogue, vous pouvez choisir l'ordre de tri croissant (A-Z) ou décroissant (Z-A), ou choisir de trier en utilisant une liste personnalisée. Vous pouvez également contrôler si les éléments supprimés des données sources sont conservés dans l'affichage du segment.
Voir aussi
- Comment masquer des lignes dans Excel : 5 méthodes simples
- Comment ajouter des sous-totaux dans Excel : Formule, Tableau croisé dynamique et Python
- Comment supprimer la mise en forme conditionnelle dans Excel : 5 méthodes simples
- C# : Ajouter, mettre à jour et supprimer des segments dans Excel
- C# : Ajouter des filtres aux tableaux croisés dynamiques dans Excel
Insertar segmentadores en Excel: Guía para principiantes sobre filtros interactivos
Tabla de contenidos
- ¿Qué es un segmentador (Slicer) en Excel?
- Por qué los segmentadores superan a los filtros tradicionales
- Requisitos previos antes de insertar segmentadores
- Cómo añadir segmentadores en Excel: Dos métodos
- Avanzado: Crear segmentadores mediante programación en Excel con C#
- Cómo usar los segmentadores de Excel una vez insertados
- Mejores prácticas para los segmentadores de Excel
- Preguntas frecuentes (FAQ)

¿Cansado de perder la pista de sus filtros de Excel dentro de interminables menús desplegables? Hay una forma mejor. Los segmentadores (slicers) convierten la tediosa exploración de datos en una experiencia visual de un solo clic, manteniendo sus selecciones visibles y sus paneles interactivos.
En esta guía, aprenderá exactamente cómo insertar segmentadores en Excel, ya sea que trabaje con tablas o tablas dinámicas. Cubriremos las mejores prácticas para crear paneles profesionales e incluso le mostraremos cómo automatizar el proceso con C#.
- ¿Qué es un segmentador en Excel?
- Por qué los segmentadores superan a los filtros tradicionales
- Requisitos previos antes de insertar segmentadores
- Cómo añadir segmentadores en Excel: Dos métodos
- Avanzado: Crear segmentadores mediante programación en Excel con C#
- Cómo usar los segmentadores de Excel una vez insertados
- Mejores prácticas para los segmentadores de Excel
- Preguntas frecuentes (FAQ)
¿Qué es un segmentador en Excel?
Un segmentador es una herramienta de filtrado visual compuesta por botones en los que se puede hacer clic y que corresponden a valores únicos en una columna de datos. En lugar de ocultar sus opciones de filtro dentro de menús desplegables, los segmentadores los muestran directamente en su hoja de cálculo, haciendo que el estado actual del filtro sea visible de un vistazo.
Piense en los segmentadores como un panel de control intuitivo para sus datos. Haga clic en un botón y su tabla, tabla dinámica o gráfico se actualizará al instante. Los botones seleccionados permanecen resaltados, por lo que usted y cualquier otro usuario siempre pueden ver qué filtros están activos.
Por qué los segmentadores superan a los filtros tradicionales
| Característica | Filtros tradicionales | Segmentadores |
|---|---|---|
| Visibilidad | El estado del filtro está oculto en menús desplegables | Los filtros seleccionados siempre están visibles |
| Facilidad de uso | Requiere varios clics para navegar por las capas del menú | Selección de botones con un solo clic para un filtrado instantáneo |
| Selección múltiple | Torpe y poco intuitivo | Mantenga presionada la tecla Ctrl o use el interruptor de selección múltiple |
| Múltiples fuentes de datos | Vinculado a una sola tabla | Puede controlar múltiples tablas dinámicas y gráficos |
| Amigable con paneles | No diseñado para paneles (dashboards) | Perfecto para paneles interactivos |
Los filtros estándar le obligan a hacer clic en una pequeña flecha, desmarcar "Seleccionar todo", desplazarse por una larga lista y hacer clic en Aceptar. En el momento en que hace clic fuera, sus opciones de filtrado desaparecen de la vista, dejándole adivinar qué es lo que está aplicado actualmente. La herramienta de segmentación de Excel resuelve este problema por completo al convertir cada opción de filtro en un botón claro y en el que se puede hacer clic, situado directamente en su hoja de cálculo.
Requisitos previos antes de insertar segmentadores
Antes de añadir segmentadores en Excel, asegúrese de que sus datos cumplan con estos requisitos:
- Formato de tabla o tabla dinámica de Excel: Los segmentadores no funcionan con rangos de celdas sin formato.
- Versión de Excel compatible: Los segmentadores están disponibles en Excel 2013 y versiones posteriores para Windows, y Excel 2016 y versiones posteriores para Mac.
- Sin filas o columnas en blanco: Las filas o columnas vacías dentro de su conjunto de datos pueden hacer que Excel interprete mal el rango completo de datos.
- Datos limpios y estructurados: Asegúrese de que cada columna tenga un encabezado único y descriptivo y un formato de datos coherente.
Para convertir un rango en una tabla, seleccione sus datos y presione "Ctrl + T", luego haga clic en Aceptar.
Cómo añadir segmentadores en Excel: Dos métodos
El proceso para insertar segmentadores depende de si está trabajando con una tabla de Excel normal o una tabla dinámica. Cubriremos ambos.
Método 1: Insertar segmentadores en una tabla de Excel
- Haga clic en cualquier lugar dentro de su tabla de Excel.
- Vaya a la pestaña Diseño de tabla en la cinta de opciones.
- Haga clic en el botón Insertar segmentación de datos en el grupo Herramientas.

- En el cuadro de diálogo emergente, marque las casillas de las columnas que desea utilizar como segmentadores (por ejemplo, Región, Producto, Categoría).
- Haga clic en Aceptar.

Excel colocará objetos de segmentación directamente en su hoja de cálculo. Cada segmentador muestra botones para todos los elementos únicos en su campo respectivo. Haga clic en cualquier botón dentro de un segmentador para filtrar la tabla al instante.

Método 2: Insertar segmentadores en una tabla dinámica
- Haga clic en cualquier celda dentro de su tabla dinámica.
- Navegue a la pestaña Analizar tabla dinámica (o pestaña Analizar, dependiendo de su versión).
- Haga clic en Insertar segmentación de datos en el grupo Filtrar.

- En el cuadro de diálogo Insertar segmentación de datos, marque las casillas de los campos por los que desea filtrar (por ejemplo, Producto).
- Haga clic en Aceptar.
Los segmentadores aparecen en su hoja y actualizan dinámicamente los resultados de la tabla dinámica. Puede moverlos, cambiarles el tamaño y darles formato para que coincidan con el diseño de su panel.

Avanzado: Crear segmentadores mediante programación en Excel con C#
Aunque los métodos manuales son perfectos para tareas únicas, es posible que necesite añadir segmentadores a cientos de archivos de Excel mediante programación. Ahí es donde entra Free Spire.XLS for .NET. Esta biblioteca gratuita le permite crear, leer y modificar archivos de Excel sin tener instalado Microsoft Office, y es totalmente compatible con la inserción de segmentadores en tablas de Excel.
Código C#: Añadir segmentadores a una tabla de Excel
A continuación, se muestra un ejemplo completo en C# que carga un archivo de Excel existente, recupera la primera tabla en la primera hoja de cálculo e inserta dos segmentadores para dos columnas diferentes. Luego, establece un nombre y un estilo integrado para cada segmentador, y guarda el resultado como un nuevo archivo .xlsx.
using Spire.Xls;
using Spire.Xls.Core;
namespace AddSlicerToTable
{
internal class Program
{
static void Main(string[] args)
{
// Cargar un archivo de Excel
Workbook workbook = new Workbook();
workbook.LoadFromFile("sampleData.xlsx");
// Obtener la primera hoja de cálculo
Worksheet worksheet = workbook.Worksheets[0];
// Obtener la primera tabla en la hoja de cálculo
IListObject table = worksheet.ListObjects[0];
// Añadir 2 segmentadores
// Parámetros: tabla, ubicación (referencia de celda), índice de columna (basado en 0)
int slicer1 = worksheet.Slicers.Add(table, "G3", 1);
int slicer2 = worksheet.Slicers.Add(table, "H5", 2);
// Establecer nombre y estilo para el segmentador
worksheet.Slicers[slicer1].Name = "Region";
worksheet.Slicers[slicer1].StyleType = SlicerStyleType.SlicerStyleLight1;
worksheet.Slicers[slicer2].Name = "Category";
worksheet.Slicers[slicer2].StyleType = SlicerStyleType.SlicerStyleDark1;
// Guardar el archivo resultante
workbook.SaveToFile("AddSlicers.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}
Cómo funciona la API de segmentadores
El método principal es Slicers.Add() con la siguiente firma:
int Add(IListObject table, string destCellName, int index);
- table: El IListObject de origen (tabla de Excel) al que está vinculado el segmentador
- destCellName: Dirección de la celda superior izquierda donde se coloca el segmentador (por ejemplo, "G3")
- index: Índice basado en 0 de la columna dentro de la tabla para usar como valores de filtro.
Nota: Los segmentadores requieren un objeto de tabla de Excel estructurado. Siempre cree y configure su tabla de Excel primero antes de llamar a la API de inserción de segmentadores.
Resultado:

Consejos adicionales para la inserción programática de segmentadores
- Múltiples tablas: Si su hoja de cálculo tiene más de una tabla, puede acceder a ellas a través de worksheet.ListObjects[index].
- Segmentadores de tablas dinámicas: Free Spire.XLS también admite la adición de segmentadores a tablas dinámicas usando
worksheet.Slicers.Add(IPivotTable, string, int). - Formatos de guardado: Use
ExcelVersion.Version2013oVersion2016para asegurarse de que los segmentadores se conserven correctamente. - Rendimiento: Al procesar varios archivos, cree una nueva instancia de Workbook para cada archivo y llame a Dispose() inmediatamente después del procesamiento para evitar fugas de memoria.
Cómo usar los segmentadores de Excel una vez insertados
Usar segmentadores es notablemente sencillo:
- Selección única: Haga clic en cualquier botón para filtrar sus datos a ese valor
- Selección múltiple: Mantenga presionada la tecla Ctrl mientras hace clic en varios botones, o haga clic en el interruptor de Selección múltiple en la parte superior del panel del segmentador
- Borrar un filtro: Haga clic en el botón Borrar filtro (el icono de embudo con una X) en la esquina superior derecha del segmentador

Mejores prácticas para los segmentadores de Excel
- Mantenga los segmentadores agrupados y alineados en la parte superior o lateral de su panel.
- Use títulos descriptivos para que los espectadores entiendan qué filtra cada segmentador.
- Limite el número de segmentadores: 3-5 suelen dar suficiente interactividad sin saturar.
- Nombre sus segmentadores en el Panel de selección (Alt + F10) para una gestión más fácil.
- Bloquee las posiciones de los segmentadores (clic derecho → Tamaño y propiedades → Propiedades → marque "No mover ni cambiar tamaño con celdas") para que permanezcan en su lugar cuando los usuarios se desplacen.
- Para la automatización, apunte siempre a ExcelVersion.Version2016 o superior para garantizar la compatibilidad del segmentador.
Reflexiones finales
Añadir segmentadores en Excel es una de las habilidades de mayor impacto para cualquiera que cree informes o paneles. Para los usuarios cotidianos, hacen que el filtrado sea intuitivo, transparente y listo para el panel, eliminando la fricción de los menús desplegables anidados. Para los desarrolladores, las API de segmentadores programáticos permiten la generación escalable y automatizada de libros de trabajo interactivos a escala empresarial.
No se conforme con hojas de cálculo estáticas que confunden a su audiencia. Empiece a usar los segmentadores de Excel hoy mismo para desbloquear todo el potencial de sus datos, convirtiendo tablas ordinarias en herramientas de toma de decisiones potentes e interactivas que impresionan e informan.
Preguntas frecuentes (FAQ)
P: ¿Puedo conectar un segmentador a varias tablas dinámicas?
R: Sí. Haga clic derecho en el segmentador → Conexiones de informe → seleccione todas las tablas dinámicas que desea controlar.
P: ¿Puedo cambiar los colores del segmentador?
R: Absolutamente. Use la pestaña Herramientas de segmentación → Opciones para aplicar estilos integrados o crear un formato personalizado.
P: ¿Funcionan los segmentadores con gráficos de Excel?
R: Sí. Si un gráfico está vinculado a una tabla o tabla dinámica que tiene un segmentador asociado, el gráfico se actualizará automáticamente para reflejar sus selecciones de segmentador.
P: ¿Puedo cambiar el orden de clasificación de los elementos dentro de un segmentador?
R: Sí. Haga clic derecho en el segmentador y seleccione Configuración de segmentación. En el cuadro de diálogo, puede elegir el orden de clasificación ascendente (A-Z) o descendente (Z-A), o elegir clasificar usando una lista personalizada. También puede controlar si los elementos eliminados de los datos de origen se conservan en la visualización del segmentador.
Ver también
Slicer in Excel einfügen: Ein Leitfaden für Anfänger zu interaktiven Filtern
Inhaltsverzeichnis
- Was ist ein Datenschnitt (Slicer) in Excel?
- Warum Datenschnitte herkömmlichen Filtern überlegen sind
- Voraussetzungen vor dem Einfügen von Datenschnitten
- So fügen Sie Datenschnitte in Excel hinzu: Zwei Methoden
- Fortgeschritten: Programmgesteuertes Erstellen von Datenschnitten in Excel mit C#
- So verwenden Sie Excel-Datenschnitte nach dem Einfügen
- Best Practices für Excel-Datenschnitte
- Häufig gestellte Fragen (FAQs)

Haben Sie es satt, in endlosen Dropdown-Menüs den Überblick über Ihre Excel-Filter zu verlieren? Es gibt einen besseren Weg. Datenschnitte (Slicer) verwandeln mühsame Datenanalysen in ein visuelles Erlebnis mit nur einem Klick, halten Ihre Auswahl sichtbar und machen Ihre Dashboards interaktiv.
In dieser Anleitung erfahren Sie genau, wie Sie Datenschnitte in Excel einfügen, egal ob Sie mit Tabellen oder Pivot-Tabellen arbeiten. Wir behandeln Best Practices für die Erstellung professioneller Dashboards und zeigen Ihnen sogar, wie Sie den Prozess mit C# automatisieren können.
- Was ist ein Datenschnitt (Slicer) in Excel?
- Warum Datenschnitte herkömmlichen Filtern überlegen sind
- Voraussetzungen vor dem Einfügen von Datenschnitten
- So fügen Sie Datenschnitte in Excel hinzu: Zwei Methoden
- Fortgeschritten: Programmgesteuertes Erstellen von Datenschnitten in Excel mit C#
- So verwenden Sie Excel-Datenschnitte nach dem Einfügen
- Best Practices für Excel-Datenschnitte
- Häufig gestellte Fragen (FAQs)
Was ist ein Datenschnitt (Slicer) in Excel?
Ein Datenschnitt ist ein visuelles Filterwerkzeug, das aus anklickbaren Schaltflächen besteht, die eindeutigen Werten in einer Datenspalte entsprechen. Anstatt Ihre Filteroptionen in Dropdown-Menüs zu verstecken, zeigt der Datenschnitt sie direkt auf Ihrem Arbeitsblatt an, sodass Ihr aktueller Filterstatus auf einen Blick sichtbar ist.
Betrachten Sie Datenschnitte als ein intuitives Bedienfeld für Ihre Daten. Klicken Sie auf eine Schaltfläche, und Ihre Tabelle, Pivot-Tabelle oder Ihr Diagramm wird sofort aktualisiert. Ausgewählte Schaltflächen bleiben hervorgehoben, sodass Sie und jeder andere Benutzer jederzeit sehen können, welche Filter aktiv sind.
Warum Datenschnitte herkömmlichen Filtern überlegen sind
| Funktion | Herkömmliche Filter | Datenschnitte |
|---|---|---|
| Sichtbarkeit | Filterstatus ist in Dropdown-Menüs versteckt | Ausgewählte Filter sind immer sichtbar |
| Benutzerfreundlichkeit | Erfordert mehrere Klicks durch Menüebenen | Ein-Klick-Auswahl für sofortige Filterung |
| Mehrfachauswahl | Umständlich und unintuitiv | Strg-Taste halten oder Mehrfachauswahl-Schalter nutzen |
| Mehrere Datenquellen | An eine Tabelle gebunden | Kann mehrere Pivot-Tabellen und Diagramme steuern |
| Dashboard-freundlich | Nicht für Dashboards konzipiert | Perfekt für interaktive Dashboards |
Standardfilter zwingen Sie dazu, auf einen kleinen Pfeil zu klicken, „Alles auswählen“ zu deaktivieren, durch eine lange Liste zu scrollen und auf OK zu klicken. Sobald Sie wegklicken, verschwinden Ihre Filterentscheidungen aus dem Blickfeld, sodass Sie raten müssen, was aktuell angewendet ist. Das Excel-Datenschnitt-Tool löst dieses Problem vollständig, indem es jede Filteroption zu einer klaren, anklickbaren Schaltfläche macht, die direkt auf Ihrem Arbeitsblatt liegt.
Voraussetzungen vor dem Einfügen von Datenschnitten
Bevor Sie Datenschnitte in Excel hinzufügen, stellen Sie sicher, dass Ihre Daten diese Anforderungen erfüllen:
- Als Excel-Tabelle oder Pivot-Tabelle formatiert: Datenschnitte funktionieren nicht mit unformatierten Rohdatenbereichen.
- Unterstützte Excel-Version: Datenschnitte sind in Excel 2013 und neuer für Windows sowie Excel 2016 und neuer für Mac verfügbar.
- Keine leeren Zeilen oder Spalten: Leere Zeilen oder Spalten innerhalb Ihres Datensatzes können dazu führen, dass Excel den vollständigen Datenbereich falsch interpretiert.
- Saubere, strukturierte Daten: Stellen Sie sicher, dass jede Spalte eine eindeutige, beschreibende Überschrift und eine konsistente Datenformatierung hat.
Um einen Bereich in eine Tabelle umzuwandeln, wählen Sie Ihre Daten aus, drücken Sie "Strg + T" und klicken Sie auf OK.
So fügen Sie Datenschnitte in Excel hinzu: Zwei Methoden
Der Prozess zum Einfügen von Datenschnitten hängt davon ab, ob Sie mit einer regulären Excel-Tabelle oder einer Pivot-Tabelle arbeiten. Wir behandeln beides.
Methode 1: Datenschnitte in eine Excel-Tabelle einfügen
- Klicken Sie irgendwo in Ihre Excel-Tabelle.
- Gehen Sie auf das Menüband zur Registerkarte Tabellenentwurf.
- Klicken Sie in der Gruppe Tools auf die Schaltfläche Datenschnitt einfügen.

- Aktivieren Sie im Dialogfeld die Kontrollkästchen für die Spalten, die Sie als Datenschnitte verwenden möchten (z. B. Region, Produkt, Kategorie).
- Klicken Sie auf OK.

Excel platziert die Datenschnitt-Objekte direkt auf Ihrem Arbeitsblatt. Jeder Datenschnitt zeigt Schaltflächen für alle eindeutigen Elemente in seinem jeweiligen Feld an. Klicken Sie auf eine beliebige Schaltfläche innerhalb eines Datenschnitts, um die Tabelle sofort zu filtern.

Methode 2: Datenschnitte in eine Pivot-Tabelle einfügen
- Klicken Sie auf eine beliebige Zelle innerhalb Ihrer Pivot-Tabelle.
- Navigieren Sie zur Registerkarte PivotTable-Analyse (oder Analysieren, je nach Version).
- Klicken Sie in der Gruppe Filtern auf Datenschnitt einfügen.

- Aktivieren Sie im Dialogfeld Datenschnitte einfügen die Kontrollkästchen für die Felder, nach denen Sie filtern möchten (z. B. Produkt).
- Klicken Sie auf OK.
Die Datenschnitte erscheinen auf Ihrem Blatt und aktualisieren dynamisch die Pivot-Tabellen-Ergebnisse. Sie können sie verschieben, in der Größe anpassen und formatieren, um sie an Ihr Dashboard-Layout anzupassen.

Fortgeschritten: Programmgesteuertes Erstellen von Datenschnitten in Excel mit C#
Während die manuellen Methoden perfekt für einmalige Aufgaben sind, müssen Sie Datenschnitte möglicherweise programmgesteuert in Hunderte von Excel-Dateien einfügen. Hier kommt Free Spire.XLS for .NET ins Spiel. Diese kostenlose Bibliothek ermöglicht es Ihnen, Excel-Dateien zu erstellen, zu lesen und zu bearbeiten, ohne dass Microsoft Office installiert sein muss – und sie unterstützt das Einfügen von Datenschnitten in Excel-Tabellen vollständig.
C#-Code: Hinzufügen von Datenschnitten zu einer Excel-Tabelle
Nachfolgend finden Sie ein vollständiges C#-Beispiel, das eine vorhandene Excel-Datei lädt, die erste Tabelle im ersten Arbeitsblatt abruft und zwei Datenschnitte für zwei verschiedene Spalten einfügt. Anschließend werden Name und ein integrierter Stil für jeden Datenschnitt festgelegt und das Ergebnis als neue .xlsx-Datei gespeichert.
using Spire.Xls;
using Spire.Xls.Core;
namespace AddSlicerToTable
{
internal class Program
{
static void Main(string[] args)
{
// Eine Excel-Datei laden
Workbook workbook = new Workbook();
workbook.LoadFromFile("sampleData.xlsx");
// Das erste Arbeitsblatt abrufen
Worksheet worksheet = workbook.Worksheets[0];
// Die erste Tabelle im Arbeitsblatt abrufen
IListObject table = worksheet.ListObjects[0];
// 2 Datenschnitte hinzufügen
// Parameter: Tabelle, Position (Zellbezug), Spaltenindex (0-basiert)
int slicer1 = worksheet.Slicers.Add(table, "G3", 1);
int slicer2 = worksheet.Slicers.Add(table, "H5", 2);
// Name und Stil für den Datenschnitt festlegen
worksheet.Slicers[slicer1].Name = "Region";
worksheet.Slicers[slicer1].StyleType = SlicerStyleType.SlicerStyleLight1;
worksheet.Slicers[slicer2].Name = "Kategorie";
worksheet.Slicers[slicer2].StyleType = SlicerStyleType.SlicerStyleDark1;
// Die Ergebnisdatei speichern
workbook.SaveToFile("AddSlicers.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}
Wie die Datenschnitt-API funktioniert
Die Kernmethode ist Slicers.Add() mit der folgenden Signatur:
int Add(IListObject table, string destCellName, int index);
- table: Das Quell-IListObject (Excel-Tabelle), an das der Datenschnitt gebunden ist
- destCellName: Adresse der oberen linken Zelle, an der der Datenschnitt platziert wird (z. B. "G3")
- index: 0-basierter Index der Spalte innerhalb der Tabelle, die als Filterwerte verwendet werden soll.
Hinweis: Datenschnitte erfordern ein strukturiertes Excel-Tabellenobjekt. Erstellen und konfigurieren Sie immer zuerst Ihre Excel-Tabelle, bevor Sie die API zum Einfügen von Datenschnitten aufrufen.
Ergebnis:

Zusätzliche Tipps für das programmgesteuerte Einfügen von Datenschnitten
- Mehrere Tabellen: Wenn Ihr Arbeitsblatt mehr als eine Tabelle enthält, können Sie über worksheet.ListObjects[index] darauf zugreifen.
- Pivot-Tabellen-Datenschnitte: Free Spire.XLS unterstützt auch das Hinzufügen von Datenschnitten zu Pivot-Tabellen unter Verwendung von
worksheet.Slicers.Add(IPivotTable, string, int). - Speicherformate: Verwenden Sie
ExcelVersion.Version2013oderVersion2016, um sicherzustellen, dass Datenschnitte korrekt erhalten bleiben. - Leistung: Erstellen Sie bei der Verarbeitung mehrerer Dateien für jede Datei eine neue Workbook-Instanz und rufen Sie nach der Verarbeitung sofort Dispose() auf, um Speicherlecks zu vermeiden.
So verwenden Sie Excel-Datenschnitte nach dem Einfügen
Die Verwendung von Datenschnitten ist bemerkenswert einfach:
- Einzelauswahl: Klicken Sie auf eine beliebige Schaltfläche, um Ihre Daten auf diesen Wert zu filtern
- Mehrfachauswahl: Halten Sie die Strg-Taste gedrückt, während Sie auf mehrere Schaltflächen klicken, oder klicken Sie auf den Mehrfachauswahl-Schalter oben im Datenschnitt-Bereich
- Filter löschen: Klicken Sie auf die Schaltfläche Filter löschen (das Trichter-Symbol mit einem X) in der oberen rechten Ecke des Datenschnitts

Best Practices für Excel-Datenschnitte
- Halten Sie Datenschnitte gruppiert und ausgerichtet am oberen oder seitlichen Rand Ihres Dashboards.
- Verwenden Sie beschreibende Beschriftungen, damit die Betrachter verstehen, was jeder Datenschnitt filtert.
- Begrenzen Sie die Anzahl der Datenschnitte – 3–5 bieten normalerweise genug Interaktivität, ohne das Bild zu überladen.
- Benennen Sie Ihre Datenschnitte im Auswahlbereich (Alt + F10) für eine einfachere Verwaltung.
- Sperren Sie die Positionen der Datenschnitte (Rechtsklick → Größe und Eigenschaften → Eigenschaften → „Von Zellen nicht verschieben oder skalieren“ aktivieren), damit sie beim Scrollen an Ort und Stelle bleiben.
- Zielen Sie bei der Automatisierung immer auf ExcelVersion.Version2016 oder höher ab, um die Kompatibilität der Datenschnitte sicherzustellen.
Abschließende Gedanken
Das Hinzufügen von Datenschnitten in Excel ist eine der wirkungsvollsten Fähigkeiten für jeden, der Berichte oder Dashboards erstellt. Für alltägliche Benutzer machen sie das Filtern intuitiv, transparent und dashboard-tauglich, wodurch die Reibung verschachtelter Dropdown-Menüs entfällt. Für Entwickler ermöglichen programmgesteuerte Datenschnitt-APIs die skalierbare, automatisierte Erstellung interaktiver Arbeitsmappen im Unternehmensmaßstab.
Geben Sie sich nicht mit statischen Tabellenkalkulationen zufrieden, die Ihr Publikum verwirren. Beginnen Sie noch heute mit der Verwendung von Excel-Datenschnitten, um das volle Potenzial Ihrer Daten auszuschöpfen – und verwandeln Sie gewöhnliche Tabellen in leistungsstarke, interaktive Entscheidungshilfen, die informieren und beeindrucken.
Häufig gestellte Fragen (FAQs)
F: Kann ich einen Datenschnitt mit mehreren Pivot-Tabellen verbinden?
A: Ja. Rechtsklick auf den Datenschnitt → Berichtsverbindungen → wählen Sie alle Pivot-Tabellen aus, die Sie steuern möchten.
F: Kann ich die Farben der Datenschnitte ändern?
A: Absolut. Verwenden Sie die Registerkarte Datenschnitttools → Optionen, um integrierte Stile anzuwenden oder benutzerdefinierte Formatierungen zu erstellen.
F: Funktionieren Datenschnitte mit Excel-Diagrammen?
A: Ja. Wenn ein Diagramm mit einer Tabelle oder Pivot-Tabelle verknüpft ist, die einen zugehörigen Datenschnitt hat, wird das Diagramm automatisch aktualisiert, um Ihre Datenschnittauswahl widerzuspiegeln.
F: Kann ich die Sortierreihenfolge der Elemente innerhalb eines Datenschnitts ändern?
A: Ja. Rechtsklick auf den Datenschnitt und wählen Sie Datenschnitteinstellungen. Im Dialogfeld können Sie die Sortierreihenfolge aufsteigend (A-Z) oder absteigend (Z-A) wählen oder eine benutzerdefinierte Liste verwenden. Sie können auch steuern, ob Elemente, die aus den Quelldaten gelöscht wurden, in der Datenschnittanzeige beibehalten werden sollen.
Siehe auch
- So blenden Sie Zeilen in Excel aus: 5 einfache Methoden
- So fügen Sie Zwischensummen in Excel hinzu: Formel, Pivot-Tabelle & Python
- So entfernen Sie bedingte Formatierung in Excel: 5 einfache Wege
- C#: Datenschnitte in Excel hinzufügen, aktualisieren und entfernen
- C#: Filter zu Pivot-Tabellen in Excel hinzufügen
Вставка срезов в Excel: руководство для начинающих по интерактивным фильтрам
Оглавление
- Что такое срез (Slicer) в Excel?
- Почему срезы лучше традиционных фильтров
- Предварительные требования перед добавлением срезов
- Как добавить срезы в Excel: два способа
- Продвинутый уровень: программное создание срезов в Excel на C#
- Как использовать срезы Excel после их добавления
- Рекомендации по работе со срезами в Excel
- Часто задаваемые вопросы (FAQ)

Устали теряться в бесконечных выпадающих списках фильтров Excel? Есть решение получше. Срезы (Slicers) превращают утомительный поиск данных в визуальный процесс в один клик, позволяя всегда видеть выбранные параметры и делая ваши отчеты интерактивными.
В этом руководстве вы узнаете, как именно вставлять срезы в Excel, работаете ли вы с обычными таблицами или сводными таблицами (PivotTables). Мы рассмотрим лучшие практики создания профессиональных дашбордов и даже покажем, как автоматизировать этот процесс с помощью C#.
- Что такое срез (Slicer) в Excel?
- Почему срезы лучше традиционных фильтров
- Предварительные требования перед добавлением срезов
- Как добавить срезы в Excel: два способа
- Продвинутый уровень: программное создание срезов в Excel на C#
- Как использовать срезы Excel после их добавления
- Рекомендации по работе со срезами в Excel
- Часто задаваемые вопросы (FAQ)
Что такое срез (Slicer) в Excel?
Срез — это инструмент визуальной фильтрации, состоящий из кнопок, соответствующих уникальным значениям в столбце данных. Вместо того чтобы скрывать параметры фильтрации внутри выпадающих меню, срезы отображают их прямо на листе, позволяя мгновенно увидеть текущее состояние фильтров.
Представьте срезы как интуитивно понятную панель управления вашими данными. Нажмите кнопку, и ваша таблица, сводная таблица или диаграмма мгновенно обновятся. Выбранные кнопки остаются подсвеченными, поэтому вы и другие пользователи всегда будете видеть, какие фильтры активны.
Почему срезы лучше традиционных фильтров
| Функция | Традиционные фильтры | Срезы |
|---|---|---|
| Видимость | Состояние фильтра скрыто в выпадающих меню | Выбранные фильтры всегда на виду |
| Простота использования | Требуется несколько кликов для навигации по меню | Выбор в один клик для мгновенной фильтрации |
| Мультивыбор | Неудобно и неинтуитивно | Удержание Ctrl или использование переключателя мультивыбора |
| Несколько источников данных | Привязаны к одной таблице | Могут управлять несколькими сводными таблицами и диаграммами |
| Удобство для дашбордов | Не предназначены для дашбордов | Идеальны для интерактивных дашбордов |
Стандартные фильтры заставляют вас нажимать на маленькую стрелку, снимать галочку «Выделить все», прокручивать длинный список и нажимать ОК. Как только вы кликаете в другое место, выбранные фильтры исчезают из виду, заставляя вас гадать, что именно сейчас отфильтровано. Инструмент «Срез» в Excel полностью решает эту проблему, превращая каждый параметр фильтрации в четкую, кликабельную кнопку прямо на вашем листе.
Предварительные требования перед добавлением срезов
Перед добавлением срезов в Excel убедитесь, что ваши данные соответствуют следующим требованиям:
- Форматирование как таблица Excel или сводная таблица: Срезы не работают с неформатированными диапазонами ячеек.
- Поддерживаемая версия Excel: Срезы доступны в Excel 2013 и более поздних версиях для Windows, а также в Excel 2016 и более поздних версиях для Mac.
- Отсутствие пустых строк или столбцов: Пустые строки или столбцы внутри набора данных могут привести к тому, что Excel неправильно определит диапазон данных.
- Чистые, структурированные данные: Убедитесь, что каждый столбец имеет уникальный описательный заголовок и единообразное форматирование данных.
Чтобы преобразовать диапазон в таблицу, выделите данные и нажмите «Ctrl + T», затем нажмите ОК.
Как добавить срезы в Excel: два способа
Процесс вставки срезов зависит от того, работаете ли вы с обычной таблицей Excel или со сводной таблицей. Мы рассмотрим оба варианта.
Способ 1: Вставка срезов в таблицу Excel
- Кликните в любом месте внутри вашей таблицы Excel.
- Перейдите на вкладку Конструктор таблиц (Table Design) на ленте.
- Нажмите кнопку Вставить срез (Insert Slicer) в группе Сервис (Tools).

- В появившемся диалоговом окне установите флажки для столбцов, которые вы хотите использовать в качестве срезов (например, Регион, Продукт, Категория).
- Нажмите ОК.

Excel разместит объекты срезов прямо на вашем листе. Каждый срез отображает кнопки для всех уникальных элементов в соответствующем поле. Нажмите любую кнопку внутри среза, чтобы мгновенно отфильтровать таблицу.

Способ 2: Вставка срезов в сводную таблицу
- Кликните любую ячейку внутри вашей сводной таблицы.
- Перейдите на вкладку Анализ сводной таблицы (PivotTable Analyze) (или «Анализ», в зависимости от версии).
- Нажмите Вставить срез (Insert Slicer) в группе Фильтр.

- В диалоговом окне Вставка срезов установите флажки для полей, по которым хотите фильтровать (например, Продукт).
- Нажмите ОК.
Срезы появятся на листе и будут динамически обновлять результаты сводной таблицы. Вы можете перемещать, изменять размер и форматировать их в соответствии с макетом вашего дашборда.

Продвинутый уровень: программное создание срезов в Excel на C#
Хотя ручные методы идеальны для разовых задач, иногда требуется программно добавить срезы в сотни файлов Excel. Здесь на помощь приходит Free Spire.XLS for .NET. Эта бесплатная библиотека позволяет создавать, читать и изменять файлы Excel без установленного Microsoft Office, и она полностью поддерживает вставку срезов в таблицы Excel.
Код C#: Добавление срезов в таблицу Excel
Ниже приведен полный пример на C#, который загружает существующий файл Excel, извлекает первую таблицу на первом листе и вставляет два среза для двух разных столбцов. Затем он задает имя и встроенный стиль для каждого среза и сохраняет результат как новый файл .xlsx.
using Spire.Xls;
using Spire.Xls.Core;
namespace AddSlicerToTable
{
internal class Program
{
static void Main(string[] args)
{
// Загрузка файла Excel
Workbook workbook = new Workbook();
workbook.LoadFromFile("sampleData.xlsx");
// Получение первого листа
Worksheet worksheet = workbook.Worksheets[0];
// Получение первой таблицы на листе
IListObject table = worksheet.ListObjects[0];
// Добавление 2 срезов
// Параметры: таблица, расположение (адрес ячейки), индекс столбца (начиная с 0)
int slicer1 = worksheet.Slicers.Add(table, "G3", 1);
int slicer2 = worksheet.Slicers.Add(table, "H5", 2);
// Установка имени и стиля для среза
worksheet.Slicers[slicer1].Name = "Region";
worksheet.Slicers[slicer1].StyleType = SlicerStyleType.SlicerStyleLight1;
worksheet.Slicers[slicer2].Name = "Category";
worksheet.Slicers[slicer2].StyleType = SlicerStyleType.SlicerStyleDark1;
// Сохранение файла
workbook.SaveToFile("AddSlicers.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}
Как работает API срезов
Основной метод — Slicers.Add() со следующей сигнатурой:
int Add(IListObject table, string destCellName, int index);
- table: Исходный объект IListObject (таблица Excel), к которому привязан срез.
- destCellName: Адрес верхней левой ячейки, где будет размещен срез (например, "G3").
- index: Индекс столбца в таблице (начиная с 0), значения которого будут использоваться для фильтрации.
Примечание: Срезы требуют наличия структурированного объекта таблицы Excel. Всегда создавайте и настраивайте таблицу Excel перед вызовом API для вставки срезов.
Результат:

Дополнительные советы по программной вставке срезов
- Несколько таблиц: Если на вашем листе более одной таблицы, вы можете получить к ним доступ через
worksheet.ListObjects[index]. - Срезы сводных таблиц: Free Spire.XLS также поддерживает добавление срезов в сводные таблицы с помощью
worksheet.Slicers.Add(IPivotTable, string, int). - Форматы сохранения: Используйте
ExcelVersion.Version2013илиVersion2016, чтобы гарантировать правильное сохранение срезов. - Производительность: При обработке нескольких файлов создавайте новый экземпляр Workbook для каждого файла и вызывайте Dispose() сразу после обработки, чтобы избежать утечек памяти.
Как использовать срезы Excel после их добавления
Использовать срезы удивительно просто:
- Одиночный выбор: Нажмите любую кнопку, чтобы отфильтровать данные по этому значению.
- Множественный выбор: Удерживайте Ctrl при нажатии нескольких кнопок или нажмите переключатель Мультивыбор в верхней части панели среза.
- Очистка фильтра: Нажмите кнопку Очистить фильтр (значок воронки с крестиком) в правом верхнем углу среза.

Рекомендации по работе со срезами в Excel
- Держите срезы сгруппированными и выровненными в верхней или боковой части вашего дашборда.
- Используйте описательные заголовки, чтобы зрители понимали, за что отвечает каждый срез.
- Ограничьте количество срезов — 3–5 штук обычно достаточно для интерактивности без перегрузки интерфейса.
- Давайте срезам понятные имена в области выделения (Alt + F10) для упрощения управления.
- Закрепляйте положение срезов (правой кнопкой мыши → Размер и свойства → Свойства → установите «Не перемещать и не изменять размеры вместе с ячейками»), чтобы они оставались на месте при прокрутке.
- Для автоматизации всегда ориентируйтесь на ExcelVersion.Version2016 или выше для обеспечения совместимости.
Заключение
Добавление срезов в Excel — один из самых эффективных навыков для тех, кто создает отчеты или дашборды. Для обычных пользователей они делают фильтрацию интуитивно понятной и прозрачной, устраняя неудобства вложенных выпадающих меню. Для разработчиков программные API для работы со срезами позволяют масштабируемо и автоматически генерировать интерактивные рабочие книги корпоративного уровня.
Не соглашайтесь на статические таблицы, которые запутывают аудиторию. Начните использовать срезы Excel уже сегодня, чтобы раскрыть весь потенциал ваших данных, превращая обычные таблицы в мощные интерактивные инструменты для принятия решений.
Часто задаваемые вопросы (FAQ)
В: Можно ли подключить один срез к нескольким сводным таблицам?
О: Да. Нажмите правой кнопкой мыши на срез → Подключения к отчету → выберите все сводные таблицы, которыми хотите управлять.
В: Можно ли изменить цвета среза?
О: Конечно. Используйте вкладку «Параметры» в разделе «Работа со срезами», чтобы применить встроенные стили или создать собственное форматирование.
В: Работают ли срезы с диаграммами Excel?
О: Да. Если диаграмма связана с таблицей или сводной таблицей, у которой есть связанный срез, диаграмма будет автоматически обновляться в соответствии с вашим выбором в срезе.
В: Можно ли изменить порядок сортировки элементов внутри среза?
О: Да. Нажмите правой кнопкой мыши на срез и выберите «Параметры среза». В диалоговом окне вы можете выбрать сортировку по возрастанию (А-Я) или по убыванию (Я-А), либо выбрать сортировку по настраиваемому списку. Вы также можете управлять тем, будут ли элементы, удаленные из исходных данных, сохраняться в отображении среза.
Смотрите также
Importing CSV/PDF Data into Excel with Spire.Agent.Office
In cross-industry data processing scenarios, importing data from CSV and PDF files into Excel is one of the most common and error-prone tasks — finance teams reconcile CSV bank statements, e-commerce teams organize order files exported from multiple platforms, and administrative staff handle PDF statements from suppliers. These files come in all shapes and formats: inconsistent CSV delimiters, fields containing commas, dates appearing in various forms, phone numbers and ID numbers that start with 0 are treated as numbers and lose their leading zeros; PDF tables cannot be edited directly, and copying them into Excel misaligns rows, columns, and merged cells.
The traditional approach is to split columns manually, set formats column by column, and hunt for erroneous cells by eye. A CSV file with a few hundred rows often takes half an hour of repeated adjustment; PDF tables can only be copied and pasted row by row. Traditional methods are also prone to misaligned columns, misplaced dates, and numbers turning into text. As data volume grows, manual processing becomes nearly impossible.
Take a finance team reconciling bank statements, for example: after receiving a CSV, the usual routine is to confirm the encoding in a text editor first, split the columns in Excel, set date and amount formats column by column, and then hunt for anomalous values by eye. A field containing a comma shifts the whole row, accounts starting with 0 lose their leading zeros, and only after repeated adjustment does the table become usable. PDF statements can only be copied and pasted row by row — rows, columns, and merged cells are almost all misaligned, and reconstructing a single statement often eats up half a day.
Comparison with Traditional SDK API Processing
| Traditional Spire.Office for .NET API | Spire.Agent.Office Processing | |
|---|---|---|
| Driving Method | Write code for column splitting, type conversion, and format checking, controlling every step | Describe the goal in natural language; the AI understands and automatically orchestrates the execution path |
| Code Volume | Data import scenarios typically require 500-1000 lines of C# code (including parsers, type conversion, error detection, etc.) | About 10 lines of calling code + one natural language instruction |
| Delimiters & Quoting | Must hand-write parsing logic for edge cases such as commas inside quotes and escape characters | The AI automatically recognizes delimiters and quoted fields and splits columns intelligently |
| Type Detection | Must hard-code date/number/text recognition rules per column; changing rules requires code changes | The AI understands data type semantics and automatically recognizes dates, numbers, and text |
| Error Detection | Must write regex and conditional checks cell by cell; coverage of error types is incomplete | The AI automatically detects anomalies such as type mismatches and column count mismatches and highlights them in red |
| Requirement Changes | Adding a new CSV variant requires modifying code → compiling → deploying | Modify the description in the instruction; takes effect immediately |
This article introduces how to use the Excel AI capabilities of Spire.Agent.Office to implement CSV smart column splitting import and PDF table import, automatically completing data type detection and highlighting erroneous formats in red, with just a single natural language instruction.
For product installation and SpireToken configuration, please refer to Integrating Spire.Agent.Office in a .NET Project. The following examples assume Spire.Agent.Office is already installed and SpireToken is configured.
CSV Smart Column Splitting Import
CSV is the most common format for data exchange, yet also the least "controllable": the delimiter may be a comma, a tab, or a semicolon; fields may contain commas or line breaks wrapped in quotes; dates, numbers, and text are mixed in the same table; values starting with 0, such as phone numbers and codes, are treated as numbers by default and lose their leading zeros. Import quality directly determines the accuracy of subsequent analysis and reports.
The following example uses the Spire.Agent.Office agent to automatically import a CSV through natural language instructions, completing smart column splitting, data type detection, and highlighting erroneous formats in red:
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Xls;
// CSV source file to be imported (passed as an attachment)
string[] attachmentPaths = new string[] { @"C:\DataImport\employee_sales_data.csv" };
// Save path of the import result document
string savePath = @"C:\DataImport\ToXLSX.xlsx";
// SpireToken Key (apply on the official website)
string key = "sk-TF***************************r";
// Natural language instruction
string instruction = "Process as follows:\n" +
"1. Convert the attached CSV file to an Excel document and apply appropriate formatting to improve readability\n" +
"2. Unify the formats of dates/sales amounts/phone numbers in the file\n" +
"3. Mark erroneous and missing data with a red background";
// AI generation
AIResult result = ImportCsvData(instruction, savePath, key, attachmentPaths);
// AI-assisted CSV import
static AIResult ImportCsvData(string instruction, string savePath, string key, string[] attachmentPaths)
{
// Configure the AI processing options
AIOptions options = new AIOptions();
options.SpireToken = key;
using (Workbook wb = new Workbook())
{
AIDocumentProcessor processor = wb.AI(options);
return processor.ExecuteInstruction(wb, instruction, savePath, attachmentPaths);
}
}
Original CSV data and smart column splitting import result

PDF Table Import to Excel
PDF is the universal format for distribution and archiving, but the table data inside it cannot be edited directly: copying it into Excel misaligns rows and columns, loses merged cells, and turns numbers and dates into text. When suppliers, banks, or government agencies deliver reports in PDF, accurately restoring the table data into editable Excel is an essential step in moving from fixed-layout documents to electronic processing.
The following example uses the Spire.Agent.Office agent to automatically extract table data from a PDF and write it into Excel through natural language instructions:
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Xls;
// PDF source file to be imported (passed as an attachment)
string[] attachmentPaths = new string[] { @"C:\DataImport\PurchaseOrder.pdf" };
// Save path of the import result document
string savePath = @"C:\DataImport\PurchaseOrderData.xlsx";
// SpireToken Key
string key = "sk-TF***************************r";
// Natural language instruction
string instruction =
"Process as follows:\n" +
"1. Convert the attached PDF file to an Excel document and apply appropriate formatting to improve readability\n" +
"2. Unify the formats of dates/sales amounts/phone numbers in the file\n" +
"3. Mark erroneous and missing data with a red background";
// AI generation
AIResult result = ImportPdfData(instruction, savePath, key, attachmentPaths);
// AI-assisted PDF import
static AIResult ImportPdfData(string instruction, string savePath, string key, string[] attachmentPaths)
{
// Configure the AI processing options
AIOptions options = new AIOptions();
options.SpireToken = key;
using (Workbook wb = new Workbook())
{
AIDocumentProcessor processor = wb.AI(options);
return processor.ExecuteInstruction(wb, instruction, savePath, attachmentPaths);
}
}
Original PDF data and table data extracted into Excel

Frequently Asked Questions
Inconsistent CSV delimiters / commas within fields cause column misalignment
Cause: The CSV delimiter may be a semicolon or a tab, or a field may contain a quoted comma or newline, which causes the whole row to shift when columns are split automatically.
Solution: Specify the delimiter in the instruction, or let the AI identify it automatically and correctly handle the quoted fields.
Numbers starting with 0 lose their leading zeros
Cause: Values starting with 0, such as phone numbers, ID numbers, and account numbers, are imported as numeric values, and the leading zeros are dropped.
Solution: Specify the relevant columns as text type in the instruction, such as "set the phone number and ID number columns to text format and preserve the leading zeros".
Obtaining a SpireToken Key
- Contact sales@e-iceblue.com or visit https://www.e-iceblue.com/TemLicense.html to obtain a trial/commercial API key
Configure it in code:
AIOptions options = new AIOptions();
options.SpireToken = key;
Automatically Extract Invoice Information with Spire.Agent.Office
In finance and tax scenarios, invoice data entry is one of the most common and time-consuming tasks. The invoice number, date, amount, tax amount and buyer on every invoice must be manually checked and entered into Excel or a financial system one by one. During mid-month reconciliation, month-end tax filing or reimbursement peak periods, the backlog of invoices often numbers in the hundreds, and manual entry speed becomes the bottleneck. The traditional approach is to open each invoice PDF page by page, find the corresponding fields, copy and paste — which is not only inefficient but also highly prone to omissions, misalignments and mistyped amounts. Any single error directly affects the accuracy of reconciliation and tax filing. Invoice layouts also vary widely, with fields in all sorts of positions, further increasing the risk of errors in manual processing. Automating the repetitive work of "reading each invoice and copying its fields" is therefore one of the pain points financial teams most urgently want to solve.
Traditional SDK API vs. Spire.Agent.Office
For "extracting fields from a PDF invoice and exporting to Excel", the traditional SDK and Spire.Agent.Office take two completely different paths. With the traditional approach, you must first figure out the field positions and page structure of every invoice, then write locating and extraction code for each field — change the layout and you must change the code. With the agent approach, you only need to describe in natural language "what to extract and what to export as"; the AI understands and orchestrates the rest:
| Traditional Spire.Office for .NET API | Spire.Agent.Office | |
|---|---|---|
| Driving approach | Write loops + conditionals + exception-handling code, controlling every step of document processing | Describe the goal in natural language; the AI understands and orchestrates the execution path |
| Code volume | Page-by-page parsing usually needs 300-600 lines of C# (page traversal, field locating, data export, etc.) | ~10 lines of calling code + 1 natural language instruction |
| Field recognition | Hard-code the page position and format of each field; layout changes require code changes | AI automatically understands the invoice layout and locates fields such as invoice number, date, amount |
| Page handling | Manually traverse every page and extract each one | AI automatically extracts page by page and aggregates |
| Data export | Manually write Excel writing logic and column layout | AI automatically generates a structured Excel with aligned fields |
| Requirement changes | Change extracted fields → change code → compile → redeploy | Modify the instruction; takes effect immediately |
From the comparison, when invoice layouts, extracted fields or export structures change frequently, the agent only needs a change of one sentence, while the traditional approach requires changing code and redeploying.
This article explains how to use the Spire.Agent.Office PDF AI capability to automatically extract the invoice number, date, amount, tax amount and buyer name from each page of a PDF invoice and export them to Excel, digitalizing your financial documents in one step.
For product installation and SpireToken configuration, please refer to Integrating Spire.Agent.Office in a .NET Project. The examples below assume Spire.Agent.Office is installed and SpireToken is configured.
Automatic Invoice Information Extraction
The core idea of automatic invoice information extraction is: pass multiple invoice PDFs to the AI agent as attachments; the agent reads each invoice, understands the layout page by page, recognizes fields such as invoice number, issue date, amount, tax ID, tax amount, buyer name and title, and aggregates them into a structured Excel. The whole process is roughly divided into three steps — first the agent reads each invoice PDF and locates the invoice fields on every page; second, it aligns the fields recognized on each page by semantics; finally, it aggregates the results into Excel and beautifies them as requested (auto-fitting column widths, adding borders, keeping numeric values with two decimal places and right-aligned). The whole "page-by-page parsing → field recognition → aggregation & beautification" process is completed automatically by the AI from a natural language instruction, without writing a separate parsing routine for each invoice or worrying about layout differences between suppliers.
For invoice PDFs with dozens or hundreds of pages, the traditional approach requires a set of locating rules for each layout, whereas with the agent approach you always maintain just one natural language instruction no matter how the invoice source or layout changes. Requirements such as the amount basis (tax-inclusive vs. tax-exclusive), column order, or whether to flag anomalies can also be written directly into the instruction and take effect immediately.
The following example uses the Spire.Agent.Office agent to automatically extract invoice information from each page of PDFs and export it to Excel through a natural language instruction:
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Pdf;
// PDF processing configuration
string key = "**************************"; // Apply for a SpireToken Key on the official website
string inputDir = @"E:\invoices"; // Directory containing invoice PDFs (multiple allowed)
string[] pdfFiles = Directory.GetFiles(inputDir, "*.pdf", SearchOption.TopDirectoryOnly);
string savePath = @"E:\output\merged.xlsx"; // Output file path (null -> auto-generated to the output directory)
string instruction =
"Read the attachment files and identify the information of each invoice, extracting the invoice number, issue date, amount, tax ID, tax amount, buyer name and title.\n" +
"Put each invoice as one row and summarize them into a single Excel table.\n" +
"When exporting to Excel, please beautify the table appropriately:\n" +
"auto-fit the column widths so that text is fully displayed; add borders to the whole data area to make rows and columns clear and readable;\n" +
"keep numeric columns such as amount and tax amount with two decimal places and right-aligned. Finally save as a well-formatted, easy-to-read Excel file.";
// Call the PDF processing function (attachments are the invoice PDFs)
AIResult result = ExecuteDemoPDF(instruction, savePath, key, pdfFiles);
// Execute PDF document AI processing
static AIResult ExecuteDemoPDF(string instruction, string savePath, string key, string[] attachments)
{
// Create an AIOptions configuration object
AIOptions options = new AIOptions();
options.SpireToken = key; // Set SpireToken Key
// Process the PDF document with a PdfDocument object
using (PdfDocument pdf = new PdfDocument())
{
// Create the AI document processor; attachments are the invoice PDFs
AIDocumentProcessor processor = pdf.AI(options);
return processor.ExecuteInstruction(pdf, instruction, savePath, attachments);
}
}
Original invoice PDF
Extracted and exported Excel 
FAQ
The extracted amount or tax amount is incorrect
Reason: The invoice amount has both uppercase and lowercase forms, or the tax-inclusive/tax-exclusive basis is inconsistent.
Solution: Specify the extraction basis clearly in the instruction (e.g., "extract the total amount including tax", "extract the amount excluding tax"); the AI agent will extract according to the specified basis. If the invoice has two forms of amount, it is also recommended to state which one takes precedence to avoid ambiguity.
How are invoices with different layouts recognized?
Reason: Invoices from different suppliers have different layouts and field positions.
Solution: The AI agent can automatically understand the invoice layout and locate fields; for unusual layouts, you can add field hints in the instruction (e.g., "the invoice number is located in the upper-right corner") to help the agent locate more accurately.
The column order / field names of the result don't match expectations
Reason: By default the AI outputs fields in the order it recognizes them.
Solution: Specify the field names and order clearly in the instruction (e.g., "export in the order: invoice number, date, amount, tax amount, buyer"), and the agent will arrange the output columns as requested.
Getting a SpireToken Key
- Contact sales@e-iceblue.com or visit https://www.e-iceblue.com/TemLicense.html to obtain a trial/commercial API key
Configure it in code:
AIOptions options = new AIOptions();
options.SpireToken = key;
Convert Excel to ODS or ODS to Excel with JavaScript in React
In daily office work, data often needs to be exchanged between Excel spreadsheets and OpenDocument spreadsheets (ODS). ODS is an open-standard spreadsheet format widely used in open-source office software such as LibreOffice and OpenOffice. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server is required. It provides simple, easy-to-use APIs that make format conversion more convenient.
With Spire.XLS for JavaScript, you can save an Excel workbook as ODS format to work seamlessly with open-source office software, or import an ODS file to create a fully formatted Excel workbook. This makes data migration between different applications more convenient and efficient.
This article covers two core features:
For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.
Convert Excel Workbook to ODS File
Exporting Excel data as ODS format makes it easy to open and edit directly in open-source office software such as LibreOffice and OpenOffice. With Spire.XLS for JavaScript, you can save an entire workbook as an ODS file, preserving table structure, styles, and data while enabling cross-platform data sharing. The steps are as follows:
- Create a
Workbookobject and load an existing Excel file. - Call the workbook's
SaveToFile()method, specifying the output filename and theFileFormat.ODSfile format. - Dispose of the workbook resources, read the result file from VFS, and trigger the download.
Below is a complete code example demonstrating how to convert Excel to ODS in React:
function App() {
const convertToODS = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font file to ensure proper text rendering
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}font/`);
// Load the sample Excel file into VFS
await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);
// Create a workbook object and load the Excel file
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: 'Sample.xlsx' });
// Save the workbook as an ODS file
const outputFileName = 'ExcelToODS.ods';
workbook.SaveToFile({ fileName: outputFileName, fileFormat: xlsModule.FileFormat.ODS });
workbook.Dispose();
// Read the file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.oasis.opendocument.spreadsheet' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert Excel to ODS</h1>
<button onClick={convertToODS}>
Generate
</button>
</div>
);
}
export default App;
Excel converted to ODS with Spire.XLS for JavaScript

Convert ODS File to Excel Workbook
Importing an ODS file into an Excel spreadsheet allows you to take full advantage of Excel's powerful formatting, calculation, and charting capabilities. Spire.XLS for JavaScript supports loading an ODS file directly via the LoadFromFile() method, which automatically detects its file format, and then you can save the workbook as an Excel file. The steps are as follows:
- Load the font file and ODS sample file into the VFS.
- Create a
Workbookobject and load the ODS file via theLoadFromFile()method. - Save the workbook as an Excel file and trigger the download.
Below is a complete code example demonstrating how to convert ODS to Excel in React:
function App() {
const convertToExcel = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font file to ensure proper text rendering
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}font/`);
// Load the ODS sample file into VFS
await window.spire.FetchFileToVFS('Sample.ods', '', `${process.env.PUBLIC_URL}data/`);
// Create a workbook object and load the ODS file
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: 'Sample.ods' });
// Save the workbook and release resources
const outputFileName = 'ODSToExcel.xlsx';
workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });
workbook.Dispose();
// Read the file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert ODS to Excel</h1>
<button onClick={convertToExcel}>
Generate
</button>
</div>
);
}
export default App;
ODS converted to Excel with Spire.XLS for JavaScript

FAQ
Why can't the generated ODS file be opened properly?
Cause: When saving the workbook with the SaveToFile() method, if the correct output file format is not specified via the fileFormat parameter, the generated file format may not match the extension, causing it to fail to open.
Solution: Specify the specific file format enum value xlsModule.FileFormat.ODS when saving as ODS:
const outputFileName = 'ExcelToODS.ods';
workbook.SaveToFile({ fileName: outputFileName, fileFormat: xlsModule.FileFormat.ODS });
How to handle the downloaded ODS file being opened as another type or unrecognized?
Cause: The MIME type is not set correctly when creating the Blob, so the browser cannot recognize the downloaded file as an ODS document, which may cause it to open as another type or display garbled text.
Solution: Specify the correct MIME type when downloading and make sure the download filename ends with .ods:
const blob = new Blob([fileArray], { type: 'application/vnd.oasis.opendocument.spreadsheet' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'ExcelToODS.ods';
a.click();
Get a Free License
Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.
Automação da geração de relatórios Excel com um agente de IA em C#
Tabela de Conteúdo

IA para Excel em C# significa combinar o julgamento de um modelo de linguagem com uma biblioteca real de processamento de Excel dentro de uma aplicação .NET, para que a aplicação possa mesclar, normalizar, analisar e formatar dados de planilhas a partir de instruções em linguagem natural em vez de código coluna por coluna. A parte difícil dos relatórios em Excel raramente foi desenhar o gráfico final — é transformar uma pilha de pastas de trabalho de origem inconsistentes em dados nos quais você realmente possa confiar. Com um agente de IA, você descreve a tarefa de relatório ("mescle estas 20 pastas de trabalho de lojas e sinalize as lojas cuja receita caiu mais de 30%") e recebe de volta uma pasta de trabalho formatada, não uma resposta em chat. O Spire.Agent.Office oferece ambas as partes: a compreensão de linguagem e uma camada de documento determinística que garante a geração de um arquivo .xlsx (ou PDF) real.
Navegação Rápida
- De Pastas de Trabalho Heterogêneas a um Modelo de Dados Comum
- Transformando Regras de Negócio em Análise em Linguagem Natural
- Da Análise a um Relatório Pronto para a Gestão
- Construindo o Fluxo de Trabalho em C#
- FAQ
1. O Real Gargalo na Automação de Relatórios do Excel
Considere a tarefa recorrente por trás da maioria das solicitações de "relatórios mensais". Uma equipe de operações administra 20 lojas regionais, e cada loja envia uma pasta de trabalho de vendas no final do mês. Em teoria, este é um único relatório. Na prática, são vinte arquivos diferentes que por acaso compartilham um padrão de nome de arquivo:
- As colunas não coincidem. Uma loja chama o valor de
Revenue, outra deSales Amount, e uma terceira deNet Sales. - O layout não coincide. Uma loja coloca os meses nas colunas, outra nas linhas, e uma terceira inclui uma coluna de notas no meio.
- Os tipos de dados não coincidem. As datas vêm como texto, os números vêm como milhares e pelo menos uma loja mescla uma linha de título no cabeçalho.
Portanto, antes que alguém possa produzir um gráfico para a gestão, um analista passa a semana abrindo arquivos, mapeando colunas, normalizando datas, procurando erros de digitação e só então verificando anomalias e montando o relatório. Nenhuma dessas tarefas faz parte da "geração de relatórios". Tudo isso é preparação de dados.
O ponto a ser internalizado: a parte difícil dos relatórios em Excel raramente é criar o gráfico final. É transformar pastas de trabalho de origem inconsistentes em dados nos quais você realmente possa confiar. Uma biblioteca de gráficos plotará dados incorretos com prazer; o que falta à equipe é um caminho confiável de arquivos de entrada brutos para uma tabela limpa e comparável. Esse caminho é exatamente onde um agente de IA muda a dinâmica.
2. O Que Muda Quando um Agente de IA Entra no Fluxo de Trabalho
A automação dessa tarefa não é nova — apenas costuma ser cara. Compare os dois fluxos de trabalho:
Automação tradicional
Inspecionar arquivos
→ mapear colunas
→ normalizar dados
→ escrever regras
→ gerar pasta de trabalho
Cada etapa antes da última é pré-definida: você escreve um mapa de colunas para cada cabeçalho conhecido, um analisador de data para cada formato conhecido e um limite para cada regra. No momento em que uma loja renomeia uma coluna ou uma regra de negócio muda, o mapa e as regras ficam incorretos, e um humano precisa intervir novamente.
Automação com agente
Descrever a tarefa de relatório
→ fornecer pastas de trabalho de origem
→ revisar o resultado
O agente lê o significado de cada pasta de trabalho em vez de uma posição fixa, portanto, o mapa de colunas e o conjunto de regras não precisam mais ser enumerados antecipadamente. O que ele remove é precisamente a parte cara: o trabalho de pré-definir um esquema e um conjunto de regras que falharão no próximo arquivo.

O restante deste artigo percorre esse pipeline uma vez, desde as pastas de trabalho brutas até um PDF impresso, usando o cenário das 20 lojas como exemplo principal. As seções 3 a 5 explicam o que o agente faz em cada etapa; a seção 6 fornece o código C# completo que o executa.
3. De Pastas de Trabalho Heterogêneas a um Modelo de Dados Comum
A versão do problema específica do Excel é que diferentes pastas de trabalho "parecem iguais" sem realmente ser iguais. Três lojas podem, cada uma, enviar uma tabela com quatro colunas e ainda assim não oferecer uma maneira de mesclá-las sem interpretação humana:
| Loja A | Loja B | Loja C |
|---|---|---|
| Revenue | Sales Amount | Net Sales |
| Month | Reporting Period | Date |
| Units | Quantity Sold | Qty |
Não existe um índice de coluna que as mapeie entre si, porque o mapeamento é semântico, e não posicional. Revenue, Sales Amount e Net Sales são três nomes para o mesmo conceito, e somente a compreensão do cabeçalho permite alinhá-los.
A etapa de consolidação do agente transforma esse alinhamento semântico em um único esquema:
Store / Region / SKU / UnitsSold / Revenue / Month
Ele lê cada pasta de trabalho de origem, resolve os nomes dos cabeçalhos em relação a esse modelo de destino, alinha linhas e colunas, ignora linhas duplicadas de cabeçalho e título e grava uma tabela normalizada. O desenvolvedor nunca escreve uma rotina FindColumnByHeader("Revenue") — a instrução nomeia o esquema de destino, e o agente determina o mapeamento a partir de cada arquivo.
Esta é a etapa com o maior retorno imediato, porque é a etapa que atualmente consome a maior parte do tempo do analista e quebra com mais frequência quando uma nova loja é adicionada.
4. Transformando Regras de Negócio em Análise em Linguagem Natural
Assim que os dados estão em um só lugar, a geração de relatórios precisa de julgamento, e o julgamento é onde as regras codificadas rigidamente falham. O exemplo prático usa uma regra financeira típica:
Sinalizar linhas onde a receita caiu mais de 30% ou cresceu mais de 50% em relação ao mês anterior.
Note o quanto está contido nessa frase e o quão inconveniente é cada parte em formato de código:
- Por que 30% e 50%? Esses são limites de negócios com contexto — uma loja sazonal, um novo SKU ou uma promoção alteram o significado de "incomum". Um
if (change < -0.30)codificado rigidamente trata cada loja de forma idêntica e dispara falsos alarmes devido à sazonalidade. - Como você altera isso? No código, você recompila e faz um novo implante (redeploy). Na instrução, o analista edita uma única frase: "caiu mais de 20%", ou "apenas para a região Leste", ou "sinalizar apenas SKUs com mais de 100 unidades vendidas".
- Adicionar uma dimensão? Quer que a regra seja aplicada por loja e por região e por mês? Você adiciona uma cláusula à instrução, não um loop aninhado.
- Explicar o resultado? O agente pode anexar uma coluna
Causecom uma explicação provável de uma frase para cada linha sinalizada — algo que uma comparação de limite por si só nunca poderá produzir.
O princípio decorrente desta seção vale a pena ser destacado claramente:
O código define como; as instruções definem o quê.
O desenvolvedor deixa de codificar a regra e passa a descrever o resultado. A regra permanece legível, editável pelos negócios e sobrevive a uma nova loja ou a uma alteração de limite sem qualquer mudança de código.
Para um exemplo prático completo da mesma análise orientada por instruções aplicada a um fluxo de trabalho de classificação (ranking), consulte o tutorial Análise e Classificação de Pontuação de Estudantes.
5. Da Análise a um Relatório Pronto para a Gestão
Encontrar anomalias é apenas metade da geração de relatórios. O resultado ainda precisa se tornar uma pasta de trabalho que alguém possa realmente usar — a planilha do analista não é o entregável; o resumo gerencial é.
O pipeline é concluído assim:
Pastas de Trabalho Brutas
↓
Dados Consolidados
↓
Anomalias
↓
Resumo Gerencial
↓
PDF
A instrução final compõe o entregável: uma aba Summary na frente com um bloco de KPIs (receita total, melhor loja, pior loja, contagem de anomalias sinalizadas), uma tabela de tendência mensal, um gráfico de barras de receita por região e formatação pronta para impressão. Apontar a mesma instrução para um caminho .pdf exporta o relatório idêntico como PDF para distribuição, sem uma etapa de renderização separada.
O ponto a ter em mente: análise e composição são dois trabalhos diferentes, e o agente faz ambos. O trabalho do analista passa a ser revisar a lista restrita sinalizada e aprovar, em vez de reconstruir a apresentação todos os meses.
6. Construindo o Fluxo de Trabalho em C#
Todas as peças acima são acionadas por um único pipeline em C#. Configure o agente uma vez e execute três instruções em sequência: consolidar, analisar e relatar. A configuração completa — token, pacotes e conexão do projeto — está documentada passo a passo no tutorial Primeiros Passos; aqui nos concentramos no próprio fluxo de trabalho.
using System.IO;
using Spire.Xls;
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
AIOptions options = new AIOptions {
SpireToken = spireToken,
WorkDir = @"C:\retail-ops\output",
TimeoutMs = 300000
};
string[] storeFiles = Directory.GetFiles(@"C:\retail-ops\inbox", "*.xlsx");
Directory.CreateDirectory(@"C:\retail-ops\output");
1. Consolidar. Passe os 20 arquivos da caixa de entrada como anexos e nomeie o esquema de destino. A normalização da seção 3 ocorre aqui, impulsionada pela instrução em vez de qualquer mapa de colunas:
using (Workbook consolidated = new Workbook())
{
AIResult result = consolidated.AI(options).ExecuteInstruction(
consolidated,
"Leia todas as pastas de trabalho de vendas regionais na caixa de entrada e mescle-as em uma única planilha. " +
"Cada loja nomeia suas colunas de forma diferente (por exemplo, Sales vs Amount, Month vs Period); " +
"normalize-as para um único esquema: Store, Region, SKU, UnitsSold, Revenue, Month. Ignore " +
"linhas de cabeçalho duplicadas e salve o resultado mesclado como uma pasta de trabalho.",
@"C:\retail-ops\output\consolidated.xlsx",
storeFiles);
if (result == null || !result.Success)
throw new InvalidOperationException($"Consolidation failed: {result?.ErrorMessage}");
}
2. Analisar. Carregue o arquivo consolidado e defina a regra da seção 4 em linguagem clara. O agente adiciona uma aba Anomalies e deixa os dados de origem intocados:
using (Workbook analysis = new Workbook())
{
analysis.LoadFromFile(@"C:\retail-ops\output\consolidated.xlsx");
AIResult result = analysis.AI(options).ExecuteInstruction(
analysis,
"Adicione uma aba 'Anomalies'. Compare a Revenue de cada loja e SKU com o mês " +
"anterior, sinalize as linhas onde a receita caiu mais de 30% ou cresceu mais de 50%, aplique " +
"um preenchimento vermelho para quedas e um preenchimento verde para aumentos, e adicione uma coluna 'Cause' com uma " +
"explicação provável de uma frase. Deixe as planilhas de dados originais inalteradas.",
@"C:\retail-ops\output\analyzed.xlsx");
if (result == null || !result.Success)
throw new InvalidOperationException($"Analysis failed: {result?.ErrorMessage}");
}
A aba Anomalies é inserida ao lado dos dados de origem, com as linhas sinalizadas, preenchimentos e a coluna Cause aplicados pela instrução:

3. Gerar Relatório. Componha o resumo gerencial da seção 5 e exporte-o. O savePath por si só escolhe o formato — .xlsx aqui, .pdf para distribuição:
using (Workbook report = new Workbook())
{
report.LoadFromFile(@"C:\retail-ops\output\analyzed.xlsx");
AIResult result = report.AI(options).ExecuteInstruction(
report,
"Produza um relatório gerencial. Adicione uma aba 'Summary' na frente com um bloco de KPIs " +
"(receita total, melhor loja, pior loja, contagem de anomalias sinalizadas), uma tabela de tendência " +
"mensal e um gráfico de barras de receita por região. Formate-o para impressão e salve a pasta de " +
"trabalho concluída.",
@"C:\retail-ops\output\monthly-report.xlsx");
if (result == null || !result.Success)
throw new InvalidOperationException($"Report generation failed: {result?.ErrorMessage}");
}
A aba Summary é colocada na frente da pasta de trabalho, pronta para impressão ou exportação em PDF:

Principais Chamadas de API
Workbook.AI(options)— anexa o processador de documentos de IA a um objeto de pasta de trabalho existenteExecuteInstruction(doc, instruction, savePath, attachments)— executa uma etapa e grava o resultadoAIResult.Success/AIResult.ErrorMessage— verifica cada etapa e exibe falhas
O Que Você Escreveria Sem o Agente
Para fins de contraste, a rota de SDK tradicional para as mesmas três etapas localiza cada coluna pela string do cabeçalho, codifica rigidamente cada limite e define cada preenchimento célula por célula — e precisa de reajuste total quando uma loja renomeia uma coluna ou a regra muda:
foreach (string file in storeFiles)
{
Workbook wb = new Workbook();
wb.LoadFromFile(file);
Worksheet sheet = wb.Worksheets[0];
// Falha no momento em que uma loja nomeia a coluna como "Sales" em vez de "Revenue".
int revenueCol = FindColumnByHeader(sheet, "Revenue");
int storeCol = FindColumnByHeader(sheet, "Store");
for (int r = sheet.LastRow; r >= 2; r--)
{
double current = double.Parse(sheet.Range[r, revenueCol].Text);
double prior = double.Parse(sheet.Range[r, revenueCol + 1].Text);
double change = (current - prior) / prior;
// Um limite codificado rigidamente; uma loja sazonal dispara falsos alarmes.
if (change < -0.30) sheet.Range[r, revenueCol].Style.Color = Color.Red;
}
// ... depois mesclar, depois resumo, depois gráfico -- centenas de linhas por loja e por mês.
}

O agente não remove a necessidade de código — ele remove a necessidade de código de mapeamento. A diferença está em onde a lógica reside: em um localizador de colunas e um limite, ou em uma frase que a equipe de negócios pode ler e editar.
7. Onde a IA Para e a Lógica da Aplicação Começa
Uma maneira mais honesta de pensar sobre essa fronteira do que uma lista do que "pode e não pode" ser feito: o agente não elimina a lógica determinística da aplicação — ele atua sobre ela.
A aplicação ainda é proprietária de tudo o que não tem a ver com a compreensão da planilha:
- Descoberta e acesso a arquivos — localizar os arquivos da caixa de entrada, verificar permissões e prepará-los
- Agendamento do fluxo de trabalho — quando o relatório é executado, com qual gatilho e em qual ordem
- Controle da fonte de dados — quais arquivos são entradas autorizadas e de onde eles vêm
- Tratamento de erros e tentativas — o que acontece quando um arquivo está ausente ou uma etapa falha
- Aprovação final — um humano revisa as anomalias sinalizadas antes da aprovação
- Reconciliação externa — comparar o relatório com um sistema de registro
O agente é responsável pelas partes que são genuinamente semânticas:
- Compreensão — ler o que cada coluna realmente significa
- Normalização — alinhar esquemas heterogêneos em um único modelo
- Interpretação — aplicar uma regra de negócio para decidir o que é incomum
- Transformação — transformar dados brutos em um resumo, gráfico e formatação
- Composição — montar a pasta de trabalho final ou PDF
Essa estrutura é mais útil do que uma tabela de recursos porque indica onde aplicar seu esforço de engenharia. Mantenha a estrutura determinística no código — onde ela é testável e auditável — e entregue o trabalho semântico ao agente. Cada lado faz o que faz de melhor.
8. Adicionando IA a um Fluxo de Trabalho Excel .NET Existente
A última coisa que vale a pena tornar explícita é o quão pouco você precisa reconstruir para chegar lá. Se sua aplicação já funciona com Excel por meio do Spire.Xls, o modelo de documento que você já possui é o ponto de integração:
Workbook
↓
Workbook.AI(options)
↓
ExecuteInstruction(...)
Você não está introduzindo uma nova camada de documento ou um serviço de processamento de documentos separado. Você está adicionando uma camada de execução em linguagem natural ao objeto Workbook que já possui. O mesmo objeto que abriu, mesclou e salvou seus arquivos agora aceita uma instrução e executa o fluxo de trabalho, com o mecanismo determinístico do Excel garantindo que a saída seja um arquivo real e bem formado — células mescladas, formatos de número e gráficos intactos. O mesmo padrão ExecuteInstruction se estende a documentos do Word e PDF — veja Revisão de Contratos com IA em C#.
Essa é a proposta de valor para um desenvolvedor Excel, declarada nos termos em que você já pensa: não "adotar uma plataforma de IA", mas sim "ensinar a pasta de trabalho que você já usa a aceitar instruções." Quando uma loja renomeia uma coluna ou a equipe financeira altera a regra de sinalização, a correção é uma edição em uma frase, e não a reconstrução do pipeline de documentos.
9. FAQ
Preciso enviar meus dados do Excel para a nuvem?
Não necessariamente. O Spire.Agent.Office é executado a partir de sua própria aplicação, portanto o SDK e o processamento de documentos permanecem dentro do seu ambiente; seus arquivos não são enviados para um serviço de terceiros para armazenamento ou conversão. Para analisar o conteúdo, a IA precisa dos dados relevantes, e estes são enviados ao modelo para processamento — uma etapa inerente a qualquer fluxo de trabalho de IA. Se você implantar seu próprio modelo em sua rede local, o conteúdo permanecerá inteiramente em sua infraestrutura. Se você se conectar por meio de uma API de modelo hospedado, como OpenAI ou Azure OpenAI, o conteúdo relevante será transmitido a esse provedor pela rede de acordo com sua configuração.
Quais formatos do Excel são suportados?
A entrada abrange arquivos de pasta de trabalho padrão, como XLSX e XLS, e o agente lê a pasta de trabalho diretamente em seu formato nativo. A saída pode ser salva como XLSX, XLS, CSV, PDF ou HTML, para que o relatório final possa ir direto para um arquivo ou lista de distribuição.
Ele pode substituir minha revisão financeira ou operacional?
Não. O agente automatiza a leitura, normalização, análise e formatação — as horas que um analista gasta todos os meses —, mas a aprovação final permanece com um revisor humano. Trate as anomalias sinalizadas como uma lista curta a ser verificada, não como uma decisão já tomada.
Qual a diferença entre isso e colar meus dados no ChatGPT?
Um modelo de chat pode informar o que parece incomum, mas não pode colocar essa resposta em uma pasta de trabalho estilizada com uma planilha de resumo, formatação condicional e um gráfico, nem pode exportar um PDF. Um agente de IA para Excel combina o julgamento do modelo de linguagem com uma camada determinística do Excel, para que a saída seja um arquivo real e bem formado que sua equipe possa abrir e distribuir.
Posso usar meu próprio modelo de IA?
Sim. O Spire.Agent.Office suporta integração flexível de modelos de IA e é compatível com as principais infraestruturas de IA, incluindo APIs de modelos hospedados e modelos implantados de forma privada. Você pode apontar o agente para seu próprio endpoint. Para dúvidas sobre quais provedores são suportados em sua implantação, entre em contato conosco.
Pronto para Automatizar seus Relatórios no Excel?
A consolidação, a análise de anomalias e a geração de relatórios são as formas mais rápidas de obter valor: aponte o agente para a caixa de entrada, descreva o relatório e obtenha uma pasta de trabalho ou PDF formatado. Siga o tutorial Primeiros Passos para executar seu primeiro fluxo de trabalho de planilha em .NET.
Leitura Adicional
- Tutorial de Automação de Análise e Classificação de Pontuação de Estudantes -- um fluxo de trabalho do Excel executado do início ao fim pelo agente
- Revisão de Contratos com IA em C# -- o mesmo padrão orientado por instruções aplicado a documentos do Word e PDF
- Visão geral do produto Spire.Agent.Office -- SDKs de agentes de IA para todos os formatos de documentos do Office
C# 기반 AI 에이전트를 활용한 Excel 보고서 생성 자동화

C# 기반 Excel AI는 .NET 애플리케이션 내에서 언어 모델의 판단력과 실제 Excel 처리 라이브러리를 결합하는 것을 의미합니다. 이를 통해 애플리케이션은 열 단위의 복잡한 코드 대신 자연어 지시사항을 기반으로 스프레드시트 데이터를 병합, 정규화, 분석 및 서식 지정할 수 있습니다. Excel 보고서 작업에서 가장 어려운 부분은 차트를 그리는 것이 아니라, 서로 다른 형식의 소스 워크북들을 실제로 신뢰할 수 있는 데이터로 변환하는 것입니다. AI 에이전트를 사용하면 보고 작업("이 20개 매장 워크북을 병합하고 매출이 30% 이상 감소한 매장을 표시해 줘")을 설명하기만 하면 단순한 채팅 답변이 아닌 서식이 지정된 워크북을 받게 됩니다. Spire.Agent.Office는 언어 이해 기능과 실제 .xlsx(또는 PDF) 파일 출력을 보장하는 결정론적 문서 레이어를 모두 제공합니다.
빠른 이동
1. Excel 보고서 자동화의 진정한 병목 현상
대부분의 "월간 보고" 요청 뒤에 숨겨진 반복적인 작업을 예로 들어보겠습니다. 운영팀은 20개의 지역 매장을 운영하고 있으며, 각 매장은 월말에 매출 워크북을 전송합니다. 이론상으로는 하나의 보고서이지만, 실제로는 파일 이름 패턴만 공유할 뿐 서로 다른 20개의 파일입니다.
- 열(Column)이 일치하지 않습니다. 한 매장은 수치를
Revenue로, 다른 매장은Sales Amount로, 세 번째 매장은Net Sales로 부릅니다. - 레이아웃이 일치하지 않습니다. 한 매장은 월을 열 방향으로, 다른 매장은 행 방향으로 배치하며, 세 번째 매장은 중간에 메모 열을 집어넣습니다.
- 데이터 형식이 일치하지 않습니다. 날짜가 텍스트로 입력되거나, 숫자에 천 단위 구분 기호가 들어가고, 최소 한 매장은 헤더 행에 제목 행을 병합해 놓습니다.
따라서 경영진을 위한 차트를 만들기 전에 분석가는 일주일 내내 파일을 열고, 열을 매핑하고, 날짜를 정규화하고, 오탈자를 찾은 후에야 비로소 이상 징후를 확인하고 보고서를 작성합니다. 이 과정 중 그 어떤 것도 "보고서 생성" 단계가 아닙니다. 모두 데이터 준비 작업일 뿐입니다.
여기서 명심해야 할 점은 Excel 보고서 작업에서 어려운 부분은 최종 차트를 만드는 것이 아니라, 일관성 없는 소스 워크북을 실제로 신뢰할 수 있는 데이터로 변환하는 것입니다. 차트 라이브러리는 잘못된 데이터라도 얼마든지 그려냅니다. 팀에 정말 필요한 것은 수신함의 원시 파일에서 깨끗하고 비교 가능한 테이블로 이어지는 신뢰할 수 있는 경로입니다. AI 에이전트는 바로 이 과정의 비효율성을 완전히 바꿔놓습니다.
2. AI 에이전트가 워크플로우에 도입되면 바뀌는 것들
이 작업을 자동화하는 것 자체는 새로운 개념이 아니지만, 기존 방식은 비쌉니다. 두 워크플로우를 비교해 보세요.
기존 자동화 방식
파일 검사
→ 열 매핑
→ 데이터 정규화
→ 규칙 작성
→ 워크북 생성
마지막 단계를 제외한 모든 단계가 사전에 정의되어야 합니다. 알려진 헤더마다 열 매핑을 작성하고, 알려진 형식마다 날짜 파서를 만들며, 각 규칙마다 임계값을 설정해야 합니다. 매장이 열 이름을 바꾸거나 비즈니스 규칙이 변경되는 순간, 매핑과 규칙은 무용지물이 되고 사람이 다시 개입해야 합니다.
에이전트 기반 자동화
보고 작업 설명
→ 소스 워크북 제공
→ 결과 검토
에이전트는 고정된 위치 대신 각 워크북의 의미(Semantic)를 읽어내므로 열 매핑과 규칙 세트를 사전에 일일이 나열할 필요가 없습니다. 이를 통해 다음 파일에서 쉽게 깨지곤 했던 스키마 및 규칙 세트의 사전 정의 작업이라는 가장 비싼 비용을 제거할 수 있습니다.

이 문서의 나머지 부분에서는 20개 매장 시나리오를 예시로 삼아 원시 워크북에서 인쇄 가능한 PDF 생성까지의 파이프라인을 살펴봅니다. 3절부터 5절까지는 각 단계에서 에이전트가 수행하는 작업을 설명하며, 6절에서는 이를 실행하는 전체 C# 코드를 제공합니다.
3. 서로 다른 워크북에서 공통 데이터 모델로
Excel 관련 문제의 특수성은 서로 다른 워크북들이 실제로는 같지 않음에도 "같아 보인다"는 점입니다. 세 매장이 각각 4개의 열이 있는 테이블을 보내오더라도 사람이 해석하지 않고는 병합할 수 없는 경우가 많습니다.
| 매장 A | 매장 B | 매장 C |
|---|---|---|
| Revenue | Sales Amount | Net Sales |
| Month | Reporting Period | Date |
| Units | Quantity Sold | Qty |
이 매핑은 위치가 아닌 의미적(Semantic) 매핑이기 때문에 서로를 직접 연결하는 열 인덱스가 존재하지 않습니다. Revenue, Sales Amount, Net Sales는 동일한 개념을 가리키는 세 가지 이름이며, 헤더의 의미를 이해해야만 맞출 수 있습니다.
에이전트의 통합 단계는 이러한 의미적 맞춤을 단일 스키마로 변환합니다.
Store / Region / SKU / UnitsSold / Revenue / Month
에이전트는 각 소스 워크북을 읽고 대상 모델에 맞게 헤더 이름을 해독하며, 행과 열을 맞추고, 중복된 헤더 및 제목 행을 건너뛰며, 하나의 정규화된 테이블을 작성합니다. 개발자는 FindColumnByHeader("Revenue")와 같은 루틴을 작성할 필요가 없습니다. 지시사항에 대상 스키마 이름을 지정하면 에이전트가 각 파일의 매핑을 스스로 해결합니다.
이 단계는 현재 분석가의 시간을 가장 많이 소모하고 새로운 매장이 추가될 때 가장 자주 깨지는 구간이므로, 자동화 시 단일 작업 기준으로 가장 큰 이점을 제공합니다.
4. 비즈니스 규칙을 자연어 분석으로 변환하기
데이터가 한곳에 모이면 보고에는 판단이 필요하며, 하드코딩된 규칙은 이 판단 단계에서 한계를 드러냅니다. 대표적인 재무 규칙 예시를 살펴보겠습니다.
전월 대비 매출이 30% 이상 감소했거나 50% 이상 증가한 행을 표시합니다.
이 한 문장에 얼마나 많은 내용이 담겨 있는지, 그리고 코드로 구현하려면 각 부분이 얼마나 까다로운지 확인해 보세요.
- 왜 30%와 50%인가? 이 숫자들은 맥락이 있는 비즈니스 임계값입니다. 계절성을 타는 매장, 신규 SKU, 또는 프로모션 행사에 따라 "이상 현상"의 기준이 달라집니다. 하드코딩된
if (change < -0.30)조건문은 모든 매장을 동일하게 취급하므로 계절성 변화에 오탐(False Alarm)을 발생시킵니다. - 규칙을 어떻게 변경하는가? 코드에서는 다시 컴파일하고 배포해야 합니다. 그러나 지시사항 방식에서는 분석가가 "20% 이상 감소"나 "동부 지역에만 적용", 또는 "100개 이상 판매된 SKU만 표시"와 같이 한 문장만 수정하면 됩니다.
- 차원을 추가하려면? 매장별, 지역별, 월별로 규칙을 적용하고 싶으신가요? 중첩 루프문 대신 지시사항에 조건절 하나만 추가하면 됩니다.
- 결과를 설명해야 하는가? 에이전트는 감지된 각 행에 대해 한 문장으로 된 유력한 설명이 담긴
Cause열을 추가할 수 있습니다. 이는 단순 임계값 비교 코드가 결코 제공할 수 없는 기능입니다.
이 내용이 전달하는 핵심 원칙은 다음과 같습니다.
코드는 '어떻게(How)'를 정의하고, 지시사항은 '무엇을(What)'할지 정의합니다.
개발자는 규칙을 일일이 코딩하는 대신 원하는 결과를 설명하기 시작합니다. 규칙은 명확하고 비즈니스 담당자가 직접 수정할 수 있는 형태로 유지되며, 매장이 추가되거나 임계값이 변경되어도 코드를 수정할 필요가 없습니다.
지시사항 기반 분석이 순위 산출 워크플로우에 적용된 전체 예제는 학생 점수 분석 및 순위 매기기 튜토리얼을 참조하세요.
5. 분석에서 경영진 보고서 작성까지
이상 징후를 찾는 것은 보고 작업의 절반에 불과합니다. 결과물은 누군가가 실제로 사용할 수 있는 워크북 형태가 되어야 합니다. 분석가의 단순 스프레드시트는 최종 제출물이 아니며, 경영진 요약 보고서가 진짜 제출물입니다.
파이프라인은 다음과 같이 완성됩니다.
원시 워크북
↓
통합 데이터
↓
이상 징후
↓
경영진 요약
↓
PDF
최종 지시사항은 결과물을 구성합니다. 맨 앞에 KPI 블록(총 매출, 최고 매출 매장, 최저 매출 매장, 감지된 이상 징후 수)이 포함된 Summary 시트를 추가하고, 월별 추이 테이블, 지역별 매출 막대 차트, 인쇄용 서식을 설정합니다. 동일한 지시사항에서 저장 경로를 .pdf로 지정하면 별도의 렌더링 단계 없이 동일한 보고서가 배포용 PDF로 내보내집니다.
여기서 얻을 수 있는 점은 분석과 구성은 서로 다른 두 가지 작업이며, 에이전트가 이 두 가지를 모두 수행한다는 것입니다. 분석가의 역할은 매달 프레젠테이션을 처음부터 다시 만드는 것이 아니라 감지된 항목을 검토하고 승인하는 것으로 전환됩니다.
6. C#으로 워크플로우 구축하기
위의 모든 단계는 하나의 C# 파이프라인으로 실행됩니다. 에이전트를 한 번 설정한 후 통합, 분석, 보고의 세 가지 지시사항을 순차적으로 실행합니다. 토큰, 패키지 및 프로젝트 연결을 포함한 전체 설정은 시작하기 튜토리얼에 단계별로 설명되어 있으며, 여기서는 워크플로우 자체에 집중합니다.
using System.IO;
using Spire.Xls;
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
AIOptions options = new AIOptions {
SpireToken = spireToken,
WorkDir = @"C:\retail-ops\output",
TimeoutMs = 300000
};
string[] storeFiles = Directory.GetFiles(@"C:\retail-ops\inbox", "*.xlsx");
Directory.CreateDirectory(@"C:\retail-ops\output");
1. 통합(Consolidate). 20개의 수신함 파일을 첨부 파일로 전달하고 대상 스키마를 지정합니다. 3절에서 설명한 정규화 작업이 열 매핑 코드 없이 지시사항에 의해 수행됩니다.
using (Workbook consolidated = new Workbook())
{
AIResult result = consolidated.AI(options).ExecuteInstruction(
consolidated,
"Read every regional sales workbook in the inbox and merge them into one worksheet. " +
"Each store names its columns differently (for example Sales vs Amount, Month vs Period); " +
"normalize them to a single schema: Store, Region, SKU, UnitsSold, Revenue, Month. Skip " +
"duplicate header rows and save the merged result as a workbook.",
@"C:\retail-ops\output\consolidated.xlsx",
storeFiles);
if (result == null || !result.Success)
throw new InvalidOperationException($"Consolidation failed: {result?.ErrorMessage}");
}
2. 분석(Analyze). 통합된 파일을 로드하고 4절의 규칙을 자연어로 명시합니다. 에이전트는 원본 데이터를 유지한 채 Anomalies 시트를 추가합니다.
using (Workbook analysis = new Workbook())
{
analysis.LoadFromFile(@"C:\retail-ops\output\consolidated.xlsx");
AIResult result = analysis.AI(options).ExecuteInstruction(
analysis,
"Add an 'Anomalies' sheet. Compare each store and SKU's Revenue against the prior " +
"month, flag rows where revenue fell by more than 30% or grew by more than 50%, apply " +
"a red fill to declines and a green fill to jumps, and add a 'Cause' column with a " +
"one-sentence likely explanation. Leave the original data sheets unchanged.",
@"C:\retail-ops\output\analyzed.xlsx");
if (result == null || !result.Success)
throw new InvalidOperationException($"Analysis failed: {result?.ErrorMessage}");
}
소스 데이터와 함께 생성된 Anomalies 시트에는 지시사항에 따라 플래그가 지정된 행, 셀 채우기 색상 및 Cause 열이 추가됩니다.

3. 보고서 생성(Report). 5절의 경영진 요약 보고서를 구성하고 내보냅니다. savePath의 확장자 지정만으로 형식이 결정됩니다(여기서는 .xlsx, 배포용은 .pdf).
using (Workbook report = new Workbook())
{
report.LoadFromFile(@"C:\retail-ops\output\analyzed.xlsx");
AIResult result = report.AI(options).ExecuteInstruction(
report,
"Produce a management report. Add a 'Summary' sheet at the front with a KPI block " +
"(total revenue, top store, bottom store, count of flagged anomalies), a monthly trend " +
"table, and a bar chart of revenue by region. Format it for print and save the finished " +
"workbook.",
@"C:\retail-ops\output\monthly-report.xlsx");
if (result == null || !result.Success)
throw new InvalidOperationException($"Report generation failed: {result?.ErrorMessage}");
}
워크북 맨 앞에 Summary 시트가 추가되어 인쇄나 PDF 내보내기가 가능한 상태로 완성됩니다.

주요 API 호출
Workbook.AI(options)— 기존 워크북 객체에 AI 문서 프로세서를 연결합니다.ExecuteInstruction(doc, instruction, savePath, attachments)— 단계를 실행하고 결과를 작성합니다.AIResult.Success/AIResult.ErrorMessage— 각 단계를 검증하고 오류 발생 시 내용을 확인합니다.
에이전트가 없을 때 작성해야 하는 코드
대조적으로, 동일한 3단계를 수행하기 위한 기존 SDK 방식은 문자열로 각 열을 찾고, 모든 임계값을 하드코딩하며, 셀별로 서식을 지정해야 합니다. 그리고 매장이 열 이름을 바꾸거나 규칙이 변경될 때마다 모든 코드를 다시 수정해야 합니다.
foreach (string file in storeFiles)
{
Workbook wb = new Workbook();
wb.LoadFromFile(file);
Worksheet sheet = wb.Worksheets[0];
// 매장이 열 이름을 "Revenue" 대신 "Sales"로 지정하는 순간 오류 발생.
int revenueCol = FindColumnByHeader(sheet, "Revenue");
int storeCol = FindColumnByHeader(sheet, "Store");
for (int r = sheet.LastRow; r >= 2; r--)
{
double current = double.Parse(sheet.Range[r, revenueCol].Text);
double prior = double.Parse(sheet.Range[r, revenueCol + 1].Text);
double change = (current - prior) / prior;
// 하드코딩된 임계값; 계절성 매장의 경우 잘못된 알림 발생.
if (change < -0.30) sheet.Range[r, revenueCol].Style.Color = Color.Red;
}
// ... 이후 병합, 요약 작성, 차트 생성 등 매장 및 월별로 수백 줄의 코드가 필요함.
}

에이전트가 코드의 필요성을 완전히 없애는 것은 아닙니다. 데이터 매핑 코드를 작성할 필요성을 없애주는 것입니다. 차이점은 로직이 위치하는 곳입니다. 열 검색 로직과 임계값 코드에 존재하는 대신, 비즈니스 담당자가 읽고 수정할 수 있는 문장에 존재하게 됩니다.
7. AI의 한계와 애플리케이션 로직의 역할
가능과 불가능의 단순 목록보다 한계를 이해하는 더 현실적인 시각은 다음과 같습니다. AI 에이전트는 결정론적인 애플리케이션 로직을 대체하는 것이 아니라, 그 위에서 작동합니다.
애플리케이션은 여전히 스프레드시트의 의미 해석과 관련 없는 다음 항목들을 담당합니다.
- 파일 검색 및 접근 권한 — 수신함 파일 검색, 권한 확인 및 파일 준비
- 워크플로우 스케줄링 — 보고서 실행 시점, 트리거 조건 및 실행 순서
- 데이터 소스 제어 — 어떤 파일이 승인된 입력값인지 및 출처 관리
- 오류 처리 및 재시도 — 파일 누락 또는 특정 단계 실패 시 대처 로직
- 최종 승인 — 최종 제출 전 사람이 감지된 이상 징후를 검토
- 외부 데이터 대조 — 생성된 보고서를 원장 시스템(System of Record)과 대조
에이전트는 의미적(Semantic) 해석이 필요한 영역을 전담합니다.
- 이해 — 각 열의 실제 의미 파악
- 정규화 — 서로 다른 스키마를 하나의 모델로 정렬
- 해석 — 비즈니스 규칙을 적용하여 이상 항목 판단
- 변환 — 원시 데이터를 요약, 차트 및 서식으로 변환
- 구성 — 최종 워크북 또는 PDF 완성
이러한 역할 분담은 엔지니어링 리소스를 어디에 투입해야 하는지 명확히 알려줍니다. 검증과 감사가 필요한 결정론적 플러밍(Plumbing) 코드는 프로그래밍 코드로 유지하고, 의미적 해석 작업은 에이전트에게 맡기는 것입니다. 각 영역이 가장 잘하는 역할을 수행하게 됩니다.
8. 기존 .NET Excel 워크플로우에 AI 추가하기
마지막으로 명확히 할 점은 이 환경을 구축하기 위해 기존 코드를 재작성할 필요가 거의 없다는 것입니다. 이미 Spire.Xls를 통해 Excel을 다루고 있는 애플리케이션이라면, 기존 문서 모델이 바로 통합 포인트가 됩니다.
Workbook
↓
Workbook.AI(options)
↓
ExecuteInstruction(...)
새로운 문서 레이어나 별도의 문서 처리 서비스를 도입할 필요가 없습니다. 기존에 사용하던 Workbook 객체에 자연어 실행 레이어를 추가하기만 하면 됩니다. 파일을 열고, 병합하고, 저장하던 동일한 객체가 이제 지시사항을 받아 워크플로우를 수행하며, 결정론적 Excel 엔진이 병합된 셀, 숫자 서식, 차트 등이 온전히 유지된 올바른 형태의 파일을 출력하도록 보장합니다. 동일한 ExecuteInstruction 패턴은 Word 및 PDF 문서에도 확장 적용할 수 있습니다. 자세한 내용은 C#을 활용한 AI 계약서 검토를 참조하세요.
이것이 Excel 개발자를 위한 핵심 가치 제안입니다. "새로운 AI 플랫폼을 도입하는 것"이 아니라 "기존에 사용하던 워크북이 지시사항을 이해하도록 만드는 것"입니다. 매장이 열 이름을 바꾸거나 재무팀이 플래그 설정 규칙을 변경할 때, 해결책은 문서 파이프라인을 다시 빌드하는 것이 아니라 문장 하나를 수정하는 것입니다.
9. 자주 묻는 질문(FAQ)
Excel 데이터를 클라우드로 전송해야 하나요?
반드시 그렇지는 않습니다. Spire.Agent.Office는 사용자 애플리케이션 내부에서 실행되므로 SDK와 문서 처리 로직이 자체 환경 내에 유지됩니다. 즉, 저장이나 변환을 위해 파일이 제3자 서비스로 업로드되지 않습니다. 콘텐츠를 분석하려면 AI 모델에 관련 데이터가 전달되어야 하며, 이는 모든 AI 워크플로우의 필수적인 과정입니다. 로컬 네트워크에 자체 AI 모델을 구축한 경우 데이터는 완전히 자체 인프라 내에 머물게 됩니다. OpenAI 또는 Azure OpenAI와 같은 호스팅된 모델 API를 연동하는 경우 설정에 따라 관련 데이터가 해당 공급업체로 전송됩니다.
어떤 Excel 형식을 지원하나요?
입력 파일로는 XLSX, XLS 등 표준 워크북 파일을 지원하며, 에이전트가 기본 형식 그대로 직접 읽어들입니다. 출력 결과물은 XLSX, XLS, CSV, PDF 또는 HTML로 저장할 수 있으므로 완성된 보고서를 아카이브나 배포 목록으로 즉시 보낼 수 있습니다.
재무 또는 운영 검토 작업을 완전히 대체할 수 있나요?
아닙니다. 에이전트는 읽기, 정규화, 분석, 서식 지정 등 분석가가 매달 소요하는 정리 작업을 자동화하지만, 최종 승인은 여전히 사람이 수행해야 합니다. 감지된 이상 항목은 이미 결정된 결론이 아니라 검토를 위한 요약 목록으로 활용해야 합니다.
ChatGPT에 데이터를 붙여넣는 것과 무엇이 다른가요?
대화형 모델은 이상 항목이 무엇인지 알려줄 수는 있지만, 그 결과를 요약 시트, 조건부 서식, 차트가 포함된 워크북으로 구성하거나 PDF로 내보낼 수 없습니다. AI Excel 에이전트는 언어 모델의 판단력과 결정론적 Excel 레이어를 결합하여, 팀이 즉시 열고 공유할 수 있는 완성된 실제 파일을 출력합니다.
자체 AI 모델을 사용할 수 있나요?
네, 가능합니다. Spire.Agent.Office는 유연한 AI 모델 연동을 지원하며, 호스팅된 모델 API 및 사설 구축(On-Premise) 모델을 포함한 주요 AI 인프라와 호환됩니다. 에이전트가 자체 엔드포인트를 바라보도록 설정할 수 있습니다. 배포 환경에서 지원되는 공급업체에 대한 문의는 문의하기를 통해 확인해 주세요.
Excel 보고서 자동화를 시작할 준비가 되셨나요?
데이터 통합, 이상 징후 분석, 보고서 생성은 AI를 통해 가장 빠르게 성과를 낼 수 있는 분야입니다. 수신함을 지정하고, 보고서를 설명하면 서식이 완료된 워크북이나 PDF를 얻을 수 있습니다. 시작하기 튜토리얼을 따라 .NET에서 첫 번째 스프레드시트 워크플로우를 실행해 보세요.
추가 자료
- 학생 점수 분석 및 순위 매기기 자동화 튜토리얼 -- 에이전트가 종단 간 실행하는 Excel 워크플로우
- C#을 활용한 AI 계약서 검토 -- Word 및 PDF 문서에 적용된 지시사항 기반 패턴
- Spire.Agent.Office 제품 개요 -- 모든 Office 문서 형식을 지원하는 AI 에이전트 SDK
Automazione della generazione di report Excel con un agente IA in C#
Indice

AI per Excel in C# significa abbinare la capacità di valutazione di un modello linguistico a una reale libreria di elaborazione Excel all'interno di un'applicazione .NET, in modo che l'applicazione possa unire, normalizzare, analizzare e formattare i dati del foglio di calcolo a partire da istruzioni in linguaggio naturale invece di codice colonna per colonna. La parte difficile del reporting Excel raramente è stata il disegno del grafico finale: è trasformare una serie di cartelle di lavoro di origine incoerenti in dati di cui ci si possa effettivamente fidare. Con un agente AI descrivi l'attività di reporting ("unisci queste 20 cartelle di lavoro dei negozi e segnala i negozi il cui fatturato è sceso di oltre il 30%") e ottieni in cambio una cartella di lavoro formattata, non una risposta di chat. Spire.Agent.Office fornisce entrambe le metà: la comprensione del linguaggio e un livello documentale deterministico che garantisce l'uscita di un vero file .xlsx (o PDF).
Navigazione rapida
- Da cartelle di lavoro eterogenee a un modello dati comune
- Trasformare le regole aziendali in analisi in linguaggio naturale
- Dall'analisi a un report pronto per la direzione
- Creazione del flusso di lavoro in C#
- FAQ
1. Il vero collo di bottiglia nell'automazione dei report Excel
Prendiamo il compito ricorrente alla base della maggior parte delle richieste di "reporting mensile". Un team operativo gestisce 20 negozi regionali e ogni negozio invia una cartella di lavoro sulle vendite a fine mese. In teoria si tratta di un solo report. In pratica sono venti file diversi che condividono per caso una struttura nel nome del file:
- Le colonne non corrispondono. Un negozio chiama la cifra
Revenue, un altroSales Amount, un terzoNet Sales. - Il layout non corrisponde. Un negozio inserisce i mesi nelle colonne, un altro nelle righe, un terzo aggiunge una colonna di note nel mezzo.
- I tipi di dati non corrispondono. Le date arrivano come testo, i numeri arrivano come migliaia e almeno un negozio unisce una riga di titolo nell'intestazione.
Quindi, prima che chiunque possa produrre un grafico per la direzione, un analista trascorre la settimana ad aprire file, mappare colonne, normalizzare date, cercare refusi e solo dopo verificare le anomalie e assemblare il report. Niente di tutto questo fa parte della "generazione del report". È tutta preparazione dei dati.
Il punto da comprendere a fondo: la parte difficile del reporting Excel raramente è la creazione del grafico finale. È trasformare cartelle di lavoro di origine incoerenti in dati di cui ci si possa effettivamente fidare. Una libreria di grafici traccerà felicemente dati errati; ciò che manca al team è un percorso affidabile dai file grezzi ricevuti a una tabella pulita e confrontabile. Quel percorso è esattamente dove un agente AI cambia le regole del gioco.
2. Cosa cambia quando un agente AI entra nel flusso di lavoro
L'automazione di questo compito non è una novità, è solo normalmente costosa. Confrontiamo i due flussi di lavoro:
Automazione tradizionale
Ispeziona i file
→ mappa le colonne
→ normalizza i dati
→ scrivi le regole
→ genera la cartella di lavoro
Ogni passaggio prima dell'ultimo è predefinito: si scrive una mappatura delle colonne per ogni intestazione nota, un parser di date per ogni formato noto e una soglia per ogni regola. Nel momento in cui un negozio rinomina una colonna o cambia una regola aziendale, la mappatura e le regole diventano errate e l'intervento umano torna ad essere necessario.
Automazione con agente
Descrivi l'attività di reporting
→ fornisci le cartelle di lavoro di origine
→ rivedi il risultato
L'agente legge il significato di ciascuna cartella di lavoro anziché basarsi su una posizione fissa, quindi la mappatura delle colonne e l'insieme di regole non devono più essere enumerati in anticipo. Ciò che rimuove è precisamente la parte più onerosa: il lavoro di predefinire uno schema e un insieme di regole che si interromperanno al file successivo.

Il resto di questo articolo esamina la pipeline dall'inizio alla fine, dalle cartelle di lavoro grezze a un PDF stampato, utilizzando lo scenario dei 20 negozi come esempio pratico. Le sezioni da 3 a 5 spiegano cosa fa l'agente in ciascuna fase; la sezione 6 fornisce il codice C# completo che la gestisce.
3. Da cartelle di lavoro eterogenee a un modello dati comune
La versione del problema specifica per Excel è che cartelle di lavoro diverse "sembrano uguali" senza esserlo davvero. Tre negozi possono inviare ciascuno una tabella con quattro colonne e non offrire comunque alcun modo di unirle senza l'interpretazione umana:
| Negozio A | Negozio B | Negozio C |
|---|---|---|
| Revenue | Sales Amount | Net Sales |
| Month | Reporting Period | Date |
| Units | Quantity Sold | Qty |
Non esiste un indice di colonna che le mappi l'una sull'altra, perché la mappatura è semantica, non posizionale. Revenue, Sales Amount e Net Sales sono tre nomi per lo stesso concetto, e solo la comprensione dell'intestazione consente di allinearli.
La fase di consolidamento dell'agente trasforma quell'allineamento semantico in un unico schema:
Store / Region / SKU / UnitsSold / Revenue / Month
Legge ogni cartella di lavoro di origine, risolve i nomi delle intestazioni rispetto a quel modello di destinazione, allinea righe e colonne, salta le righe di intestazione e titolo duplicate e scrive una tabella normalizzata. Lo sviluppatore non deve mai scrivere una routine FindColumnByHeader("Revenue"): l'istruzione specifica lo schema target e l'agente elabora la mappatura da ciascun file.
Questa è la fase con il massimo ritorno immediato, perché è quella che attualmente richiede più tempo all'analista e che si blocca più spesso quando si aggiunge un nuovo negozio.
4. Trasformare le regole aziendali in analisi in linguaggio naturale
Una volta che i dati sono raccolti in un unico posto, il reporting richiede valutazione, ed è proprio nella valutazione che le regole hardcoded falliscono. L'esempio in esame utilizza una tipica regola finanziaria:
Segnala le righe in cui il fatturato è sceso di oltre il 30% o è cresciuto di oltre il 50% rispetto al mese precedente.
Notate quanti elementi sono racchiusi in quella frase e quanto sia complessa ciascuna parte se tradotta in codice:
- Perché il 30% e il 50%? Sono soglie aziendali legate a un contesto: un negozio stagionale, un nuovo SKU o una promozione modificano il significato di "insolito". Una condizione hardcoded
if (change < -0.30)tratta ogni negozio allo stesso modo e genera falsi allarmi sulla stagionalità. - Come si modifica? Nel codice, occorre ricompilare ed eseguire nuovamente il deployment. Nell'istruzione, l'analista modifica semplicemente una frase: "sceso di oltre il 20%", oppure "solo per la regione Est", oppure "segnala solo gli SKU con più di 100 unità vendute".
- Aggiungere una dimensione? Si desidera applicare la regola per negozio e per regione e per mese? Si aggiunge una clausola all'istruzione, non un ciclo annidato.
- Spiegare il risultato? L'agente può aggiungere una colonna
Causecon una probabile spiegazione in una sola frase per ciascuna riga segnalata — qualcosa che un semplice confronto di soglie non potrebbe mai produrre.
Il principio che emerge da questa sezione merita di essere enunciato chiaramente:
Il codice definisce il come; le istruzioni definiscono il cosa.
Lo sviluppatore smette di codificare la regola e inizia a descrivere il risultato. La regola rimane leggibile, modificabile dal business e sopravvive all'aggiunta di un nuovo negozio o a un cambio di soglia senza richiedere modifiche al codice.
Per un esempio completo ed esercitato della stessa analisi basata su istruzioni applicata a un flusso di lavoro di graduatoria, consultare il tutorial sull'Analisi e Classificazione dei Punteggi degli Studenti.
5. Dall'analisi a un report pronto per la direzione
Trovare le anomalie è solo metà del lavoro di reporting. Il risultato deve comunque diventare una cartella di lavoro che qualcuno possa effettivamente utilizzare: il foglio di calcolo dell'analista non è il deliverable finale; lo è il riepilogo per la direzione.
La pipeline si completa in questo modo:
Cartelle di lavoro grezze
↓
Dati consolidati
↓
Anomalie
↓
Riepilogo per la direzione
↓
PDF
L'istruzione finale compone il documento finale: un foglio Summary all'inizio con un blocco KPI (fatturato totale, miglior negozio, peggior negozio, conteggio delle anomalie segnalate), una tabella con il trend mensile, un grafico a barre del fatturato per regione e una formattazione pronta per la stampa. Indirizzando la stessa istruzione su un percorso .pdf si esporta l'identico report in formato PDF per la distribuzione, senza alcuna fase di rendering separata.
Il concetto chiave da ricordare: l'analisi e la composizione sono due compiti diversi e l'agente li esegue entrambi. Il lavoro dell'analista diventa la revisione della selezione di elementi segnalati e la relativa approvazione, anziché la ricostruzione del report ogni mese.
6. Creazione del flusso di lavoro in C#
Tutti i componenti sopra descritti sono gestiti da una sola pipeline C#. È sufficiente configurare l'agente una volta e poi eseguire tre istruzioni in sequenza: consolida, analizza, rendiconta. La configurazione completa (token, pacchetti e collegamento del progetto) è documentata passo dopo passo nel tutorial Guida introduttiva; qui ci concentriamo sul flusso di lavoro stesso.
using System.IO;
using Spire.Xls;
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
AIOptions options = new AIOptions {
SpireToken = spireToken,
WorkDir = @"C:\retail-ops\output",
TimeoutMs = 300000
};
string[] storeFiles = Directory.GetFiles(@"C:\retail-ops\inbox", "*.xlsx");
Directory.CreateDirectory(@"C:\retail-ops\output");
1. Consolida. Passa i 20 file della cartella inbox come allegati e indica lo schema di destinazione. La normalizzazione descritta nella sezione 3 avviene qui, guidata dall'istruzione anziché da una mappatura delle colonne:
using (Workbook consolidated = new Workbook())
{
AIResult result = consolidated.AI(options).ExecuteInstruction(
consolidated,
"Leggi ogni cartella di lavoro delle vendite regionali nella cartella inbox e uniscile in un unico foglio di lavoro. " +
"Ogni negozio denomina le colonne diversamente (ad esempio Sales rispetto ad Amount, Month rispetto a Period); " +
"normalizzale in un unico schema: Store, Region, SKU, UnitsSold, Revenue, Month. Salta " +
"le righe di intestazione duplicate e salva il risultato unito come cartella di lavoro.",
@"C:\retail-ops\output\consolidated.xlsx",
storeFiles);
if (result == null || !result.Success)
throw new InvalidOperationException($"Consolidation failed: {result?.ErrorMessage}");
}
2. Analizza. Carica il file consolidato ed esprimi la regola descritta nella sezione 4 in linguaggio naturale. L'agente aggiunge un foglio Anomalies e lascia inalterati i dati di origine:
using (Workbook analysis = new Workbook())
{
analysis.LoadFromFile(@"C:\retail-ops\output\consolidated.xlsx");
AIResult result = analysis.AI(options).ExecuteInstruction(
analysis,
"Aggiungi un foglio 'Anomalies'. Confronta il fatturato (Revenue) di ciascun negozio e SKU rispetto al mese " +
"precedente, segnala le righe in cui il fatturato è sceso di oltre il 30% o è cresciuto di oltre il 50%, applica " +
"un riempimento rosso ai cali e un riempimento verde agli aumenti, e aggiungi una colonna 'Cause' con " +
"una probabile spiegazione in una sola frase. Lascia invariati i fogli dati originali.",
@"C:\retail-ops\output\analyzed.xlsx");
if (result == null || !result.Success)
throw new InvalidOperationException($"Analysis failed: {result?.ErrorMessage}");
}
Il foglio Anomalies viene affiancato ai dati di origine, con le righe segnalate, i riempimenti e la colonna Cause applicati dall'istruzione:

3. Rendiconta. Componi il riepilogo per la direzione descritto nella sezione 5 ed esportalo. Il solo parametro savePath determina il formato — .xlsx in questo caso, .pdf per la distribuzione:
using (Workbook report = new Workbook())
{
report.LoadFromFile(@"C:\retail-ops\output\analyzed.xlsx");
AIResult result = report.AI(options).ExecuteInstruction(
report,
"Produci un report per la direzione. Aggiungi un foglio 'Summary' all'inizio con un blocco KPI " +
"(fatturato totale, miglior negozio, peggior negozio, conteggio delle anomalie segnalate), una tabella " +
"del trend mensile e un grafico a barre del fatturato per regione. Formattalo per la stampa e salva " +
"la cartella di lavoro completata.",
@"C:\retail-ops\output\monthly-report.xlsx");
if (result == null || !result.Success)
throw new InvalidOperationException($"Report generation failed: {result?.ErrorMessage}");
}
Il foglio Summary viene posizionato all'inizio della cartella di lavoro, pronto per la stampa o l'esportazione in PDF:

Chiamate API principali
Workbook.AI(options)— allega il processore di documenti AI a un oggetto workbook esistenteExecuteInstruction(doc, instruction, savePath, attachments)— esegue una fase e scrive il risultatoAIResult.Success/AIResult.ErrorMessage— verifica ciascuna fase ed evidenzia gli errori
Cosa bisognerebbe scrivere senza l'agente
Per un confronto, l'approccio SDK tradizionale per le stesse tre fasi individua ciascuna colonna tramite la stringa dell'intestazione, imposta ogni soglia nel codice e definisce ogni riempimento cella per cella — richiedendo la ricalibrazione di tutto quando un negozio rinomina una colonna o la regola cambia:
foreach (string file in storeFiles)
{
Workbook wb = new Workbook();
wb.LoadFromFile(file);
Worksheet sheet = wb.Worksheets[0];
// Fallisce nel momento in cui un negozio chiama la colonna "Sales" invece di "Revenue".
int revenueCol = FindColumnByHeader(sheet, "Revenue");
int storeCol = FindColumnByHeader(sheet, "Store");
for (int r = sheet.LastRow; r >= 2; r--)
{
double current = double.Parse(sheet.Range[r, revenueCol].Text);
double prior = double.Parse(sheet.Range[r, revenueCol + 1].Text);
double change = (current - prior) / prior;
// Una soglia hardcoded; un negozio stagionale genera falsi allarmi.
if (change < -0.30) sheet.Range[r, revenueCol].Style.Color = Color.Red;
}
// ... poi unione, poi riepilogo, poi grafico -- centinaia di righe per negozio e per mese.
}

L'agente non elimina la necessità di codice — elimina la necessità di codice di mappatura. La differenza sta in dove risiede la logica: in un rilevatore di colonne e una soglia, oppure in una frase che il business può leggere e modificare.
7. Dove l'AI si ferma e inizia la logica dell'applicazione
Un modo più realistico di considerare il confine rispetto a un elenco di ciò che "può e non può fare": l'agente non elimina la logica deterministica dell'applicazione — si posiziona al di sopra di essa.
L'applicazione gestisce comunque tutto ciò che non ha a che fare con la comprensione del foglio di calcolo:
- Individuazione e accesso ai file — individuare i file della cartella inbox, verificare i permessi e prepararli
- Pianificazione del flusso di lavoro — quando viene eseguito il report, con quale trigger e in quale ordine
- Controllo delle fonti dati — quali file sono input autorizzati e da dove provengono
- Gestione degli errori e tentativi di ripristino — cosa succede quando un file è mancante o una fase fallisce
- Approvazione finale — un operatore umano esamina le anomalie segnalate prima dell'approvazione
- Riconciliazione esterna — confronto del report con un sistema di registrazione di riferimento
L'agente gestisce le parti genuinamente semantiche:
- Comprensione — lettura del reale significato di ciascuna colonna
- Normalizzazione — allineamento di schemi eterogenei in un unico modello
- Interpretazione — applicazione di una regola aziendale per decidere cosa è insolito
- Trasformazione — conversione dei dati grezzi in un riepilogo, un grafico e formattazione
- Composizione — assemblaggio della cartella di lavoro finale o del PDF
Questa impostazione è più utile di una tabella delle funzionalità perché indica dove concentrare lo sforzo ingegneristico. Mantenete la struttura deterministica nel codice — dove è testabile e verificabile — e affidate il lavoro semantico all'agente. Ciascuna parte fa ciò in cui riesce meglio.
8. Aggiungere l'AI a un flusso di lavoro Excel .NET esistente
L'ultimo aspetto che vale la pena esplicitare è quanto poco sia necessario ricostruire per raggiungere questo risultato. Se la vostra applicazione funziona già con Excel tramite Spire.Xls, il modello documentale che già possedete rappresenta il punto di integrazione:
Workbook
↓
Workbook.AI(options)
↓
ExecuteInstruction(...)
Non state introducendo un nuovo livello documentale o un servizio di elaborazione documenti separato. State aggiungendo un livello di esecuzione in linguaggio naturale all'oggetto Workbook che già possedete. Lo stesso oggetto che aprirà, unirà e salverà i vostri file accetta ora un'istruzione ed esegue il flusso di lavoro, con il motore Excel deterministico che garantisce che l'output sia un file reale e ben formato — celle unite, formati numerici e grafici compresi. Lo stesso modello ExecuteInstruction si estende ai documenti Word e PDF — vedere Revisione dei contratti con AI in C#.
Questa è la proposta di valore per uno sviluppatore Excel, espressa nei termini in cui già ragiona: non "adottare una piattaforma AI", ma "insegnare alla cartella di lavoro che già si utilizza a ricevere istruzioni". Quando un negozio rinomina una colonna o il team finanziario modifica la regola di segnalazione, la soluzione consiste nella modifica di una frase, non nella ricostruzione della pipeline documentale.
9. FAQ
Devo inviare i miei dati Excel al cloud?
Non necessariamente. Spire.Agent.Office viene eseguito direttamente dalla tua applicazione, quindi l'SDK e l'elaborazione dei documenti rimangono all'interno del tuo ambiente; i tuoi file non vengono caricati su un servizio di terze parti per l'archiviazione o la conversione. Per analizzare i contenuti, l'AI necessita dei dati pertinenti, che vengono inviati al modello per l'elaborazione — un passaggio intrinseco di qualsiasi flusso di lavoro AI. Se distribuisci un tuo modello sulla tua rete locale, il contenuto rimane interamente all'interno della tua infrastruttura. Se ti colleghi tramite un'API di un modello ospitato come OpenAI o Azure OpenAI, i contenuti pertinenti vengono trasmessi a tale provider tramite la rete in base alla tua configurazione.
Quali formati Excel sono supportati?
L'input supporta i file di cartella di lavoro standard come XLSX e XLS e l'agente legge la cartella di lavoro direttamente nel suo formato nativo. L'output può essere salvato come XLSX, XLS, CSV, PDF o HTML, consentendo di inviare il report finale direttamente ad un archivio o a un elenco di distribuzione.
Può sostituire la revisione finanziaria o operativa?
No. L'agente automatizza la lettura, la normalizzazione, l'analisi e la formattazione — le ore che un analista dedica ogni mese —, ma l'approvazione finale rimane a carico di un revisore umano. Le anomalie segnalate vanno considerate come un elenco di elementi da verificare, non come una decisione già presa.
In che modo questo differisce dall'incollare i miei dati in ChatGPT?
Un modello di chat può indicare cosa appare insolito, ma non può inserire tale risposta in una cartella di lavoro formattata con un foglio di riepilogo, formattazione condizionale e un grafico, né può esportare un PDF. Un agente AI per Excel unisce la capacità di valutazione del modello linguistico a un livello Excel deterministico, in modo che l'output sia un file reale e ben formato che il team può aprire e distribuire.
Posso utilizzare un mio modello AI?
Sì. Spire.Agent.Office supporta l'integrazione flessibile con modelli AI ed è compatibile con le principali infrastrutture AI, comprese le API di modelli ospitati e modelli distribuiti privatamente. È possibile indirizzare l'agente verso il proprio endpoint. Per domande relative ai provider supportati nella propria distribuzione, contattaci.
Pronto ad automatizzare i tuoi report Excel?
Consolidamento, analisi delle anomalie e generazione di report sono i punti in cui ottenere valore più rapidamente: indirizza l'agente sulla cartella inbox, descrivi il report e ottieni una cartella di lavoro o un PDF formattato. Segui il tutorial Guida introduttiva per eseguire il tuo primo flusso di lavoro su fogli di calcolo in .NET.
Ulteriori letture
- Tutorial sull'automatizzazione dell'analisi e classificazione dei punteggi degli studenti -- un flusso di lavoro Excel che l'agente esegue dall'inizio alla fine
- Revisione dei contratti con AI in C# -- lo stesso modello basato su istruzioni applicato a documenti Word e PDF
- Panoramica del prodotto Spire.Agent.Office -- SDK con agente AI per ogni formato di documento Office