Explore como inserir segmentadores de dados para tabelas e tabelas dinâmicas do Excel

Cansado de perder o controle dos seus filtros do Excel dentro de menus suspensos intermináveis? Existe uma maneira melhor. Os Segmentadores de Dados (Slicers) transformam a exploração de dados tediosa em uma experiência visual de um clique, mantendo suas seleções visíveis e seus painéis interativos.

Neste guia, você aprenderá exatamente como inserir segmentadores no Excel, esteja você trabalhando com tabelas ou Tabelas Dinâmicas. Abordaremos as melhores práticas para criar painéis profissionais e até mostraremos como automatizar o processo com C#.


O que é um Segmentador de Dados no Excel?

Um segmentador é uma ferramenta de filtragem visual composta por botões clicáveis que correspondem a valores únicos em uma coluna de dados. Em vez de ocultar suas opções de filtro dentro de menus suspensos, os segmentadores as exibem diretamente na sua planilha, tornando o estado atual do filtro visível rapidamente.

Pense nos segmentadores como um painel de controle intuitivo para seus dados. Clique em um botão e sua tabela, Tabela Dinâmica ou gráfico será atualizado instantaneamente. Os botões selecionados permanecem destacados, para que você e qualquer outro usuário possam sempre ver quais filtros estão ativos.


Por que os Segmentadores superam os filtros tradicionais

Recurso Filtros Tradicionais Segmentadores
Visibilidade O estado do filtro fica oculto em menus suspensos Os filtros selecionados estão sempre visíveis
Facilidade de uso Requer vários cliques para navegar pelas camadas do menu Seleção de botão com um clique para filtragem instantânea
Seleção múltipla Desajeitada e pouco intuitiva Segure Ctrl ou use a alternância de Seleção Múltipla
Múltiplas fontes de dados Vinculado a uma única tabela Pode controlar múltiplas Tabelas Dinâmicas e gráficos
Amigável para painéis Não projetado para painéis Perfeito para painéis interativos

Os filtros padrão forçam você a clicar em uma pequena seta, desmarcar "Selecionar Tudo", rolar por uma longa lista e clicar em OK. No momento em que você clica fora, suas escolhas de filtro desaparecem da vista, deixando você adivinhando o que está aplicado no momento. A ferramenta de segmentação do Excel resolve esse problema completamente, tornando cada opção de filtro um botão claro e clicável que fica diretamente na sua planilha.


Pré-requisitos antes de inserir Segmentadores

Antes de adicionar segmentadores no Excel, certifique-se de que seus dados atendam a estes requisitos:

  • Formatado como Tabela ou Tabela Dinâmica do Excel: Os segmentadores não funcionam com intervalos de células brutos não formatados.
  • Versão do Excel compatível: Os segmentadores estão disponíveis no Excel 2013 e posterior para Windows, e Excel 2016 e posterior para Mac.
  • Sem linhas ou colunas em branco: Linhas ou colunas vazias dentro do seu conjunto de dados podem fazer com que o Excel interprete mal o intervalo completo de dados.
  • Dados limpos e estruturados: Certifique-se de que cada coluna tenha um cabeçalho único e descritivo e uma formatação de dados consistente.

Para converter um intervalo em uma tabela, selecione seus dados e pressione "Ctrl + T", depois clique em OK.


Como adicionar Segmentadores no Excel: Dois métodos

O processo para inserir segmentadores depende se você está trabalhando com uma Tabela do Excel comum ou uma Tabela Dinâmica. Abordaremos ambos.

Método 1: Inserir Segmentadores em uma Tabela do Excel

  • Clique em qualquer lugar dentro da sua tabela do Excel.
  • Vá para a guia Design da Tabela na faixa de opções.
  • Clique no botão Inserir Segmentação de Dados no grupo Ferramentas.

O botão Inserir Segmentação de Dados na guia Design da Tabela.

  • Na caixa de diálogo pop-up, marque as caixas das colunas que você deseja usar como segmentadores (por exemplo, Região, Produto, Categoria).
  • Clique em OK.

Caixa de diálogo Inserir Segmentação de Dados do Excel listando as colunas da tabela.

O Excel colocará objetos de segmentação diretamente na sua planilha. Cada segmentador exibe botões para todos os itens únicos em seu respectivo campo. Clique em qualquer botão dentro de um segmentador para filtrar a tabela instantaneamente.

Planilha do Excel contendo uma tabela de dados de vendas com três segmentadores.

Método 2: Inserir Segmentadores em uma Tabela Dinâmica

  • Clique em qualquer célula dentro da sua tabela dinâmica.
  • Navegue até a guia Análise de Tabela Dinâmica (ou guia Analisar, dependendo da sua versão).
  • Clique em Inserir Segmentação de Dados no grupo Filtrar.

O botão Inserir Segmentação de Dados na guia Análise de Tabela Dinâmica.

  • Na caixa de diálogo Inserir Segmentação de Dados, marque as caixas dos campos pelos quais você deseja filtrar (por exemplo, Produto).
  • Clique em OK.

Os segmentadores aparecem na sua planilha e atualizam dinamicamente os resultados da Tabela Dinâmica. Você pode movê-los, redimensioná-los e formatá-los para combinar com o layout do seu painel.

Uma Tabela Dinâmica resumindo a receita total por produto combinada com um segmentador de Produto.


Avançado: Criar Segmentadores programaticamente no Excel com C#

Embora os métodos manuais sejam perfeitos para tarefas pontuais, você pode precisar adicionar segmentadores a centenas de arquivos do Excel programaticamente. É aí que entra o Free Spire.XLS for .NET. Esta biblioteca gratuita permite criar, ler e modificar arquivos do Excel sem o Microsoft Office instalado — e ela oferece suporte total à inserção de segmentadores em tabelas do Excel.

Código C#: Adicionando Segmentadores a uma Tabela do Excel

Abaixo está um exemplo completo em C# que carrega um arquivo do Excel existente, recupera a primeira tabela na primeira planilha e insere dois segmentadores para duas colunas diferentes. Em seguida, ele define um nome e um estilo integrado para cada segmentador e salva o resultado como um novo arquivo .xlsx.

using Spire.Xls;
using Spire.Xls.Core;

namespace AddSlicerToTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Carregar um arquivo do Excel
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("sampleData.xlsx");

            // Obter a primeira planilha
            Worksheet worksheet = workbook.Worksheets[0];

            // Obter a primeira tabela na planilha
            IListObject table = worksheet.ListObjects[0];

            // Adicionar 2 segmentadores
            // Parâmetros: tabela, localização (referência de célula), índice da coluna (baseado em 0)
            int slicer1 = worksheet.Slicers.Add(table, "G3", 1);
            int slicer2 = worksheet.Slicers.Add(table, "H5", 2);

            // Definir nome e estilo para o segmentador
            worksheet.Slicers[slicer1].Name = "Região";
            worksheet.Slicers[slicer1].StyleType = SlicerStyleType.SlicerStyleLight1;
            worksheet.Slicers[slicer2].Name = "Categoria";
            worksheet.Slicers[slicer2].StyleType = SlicerStyleType.SlicerStyleDark1;

            // Salvar o arquivo de resultado
            workbook.SaveToFile("AddSlicers.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}

Como funciona a API de Segmentação

O método principal é Slicers.Add() com a seguinte assinatura:

int Add(IListObject table, string destCellName, int index);
  • table: O IListObject (Tabela do Excel) de origem ao qual o segmentador está vinculado
  • destCellName: Endereço da célula superior esquerda onde o segmentador é colocado (por exemplo, "G3")
  • index: Índice baseado em 0 da coluna dentro da tabela a ser usada como valores de filtro.

Nota: Os segmentadores exigem um objeto de Tabela do Excel estruturado. Sempre crie e configure sua tabela do Excel antes de chamar a API de inserção de segmentação.

Resultado:

Inserir dois segmentadores do Excel usando C# com a biblioteca Free Spire.XLS

Dicas adicionais para inserção programática de segmentadores

  • Múltiplas tabelas: Se sua planilha tiver mais de uma tabela, você pode acessá-las via worksheet.ListObjects[index].
  • Segmentadores de Tabela Dinâmica: O Free Spire.XLS também oferece suporte à adição de segmentadores a Tabelas Dinâmicas usando worksheet.Slicers.Add(IPivotTable, string, int).
  • Formatos de salvamento: Use ExcelVersion.Version2013 ou Version2016 para garantir que os segmentadores sejam preservados corretamente.
  • Desempenho: Ao processar vários arquivos, crie uma nova instância de Workbook para cada arquivo e chame Dispose() imediatamente após o processamento para evitar vazamentos de memória.

Como usar os Segmentadores do Excel após inseri-los

Usar segmentadores é notavelmente simples:

  • Seleção única: Clique em qualquer botão para filtrar seus dados para esse valor
  • Seleção múltipla: Segure Ctrl enquanto clica em vários botões, ou clique na alternância Seleção Múltipla na parte superior do painel do segmentador
  • Limpar um filtro: Clique no botão Limpar Filtro (o ícone de funil com um X) no canto superior direito do segmentador

Um painel de segmentação do Excel mostrando a Seleção Múltipla, o botão Limpar Filtro e uma lista vertical de valores de filtro.


Melhores práticas para Segmentadores do Excel

  1. Mantenha os segmentadores agrupados e alinhados na parte superior ou lateral do seu painel.
  2. Use legendas descritivas para que os espectadores entendam o que cada segmentador filtra.
  3. Limite o número de segmentadores — 3 a 5 geralmente oferecem interatividade suficiente sem sobrecarregar.
  4. Nomeie seus segmentadores no Painel de Seleção (Alt + F10) para facilitar o gerenciamento.
  5. Bloqueie as posições dos segmentadores (clique com o botão direito → Tamanho e Propriedades → Propriedades → marque "Não mover ou dimensionar com células") para que eles permaneçam no lugar quando os usuários rolarem a página.
  6. Para automação, sempre direcione para ExcelVersion.Version2016 ou superior para garantir a compatibilidade do segmentador.

Considerações Finais

Adicionar segmentadores no Excel é uma das habilidades de maior impacto para quem cria relatórios ou painéis. Para usuários comuns, eles tornam a filtragem intuitiva, transparente e pronta para painéis, eliminando o atrito de menus suspensos aninhados. Para desenvolvedores, as APIs de segmentação programática permitem a geração escalável e automatizada de pastas de trabalho interativas em escala empresarial.

Não se contente com planilhas estáticas que confundem seu público. Comece a usar os segmentadores do Excel hoje para desbloquear todo o potencial dos seus dados — transformando tabelas comuns em ferramentas de tomada de decisão poderosas e interativas que impressionam e informam.


Perguntas Frequentes (FAQs)

P: Posso conectar um segmentador a várias Tabelas Dinâmicas?

R: Sim. Clique com o botão direito no segmentador → Conexões de Relatório → selecione todas as Tabelas Dinâmicas que você deseja controlar.

P: Posso alterar as cores do segmentador?

R: Com certeza. Use a guia Ferramentas de Segmentação → Opções para aplicar estilos integrados ou criar formatação personalizada.

P: Os segmentadores funcionam com gráficos do Excel?

R: Sim. Se um gráfico estiver vinculado a uma Tabela ou Tabela Dinâmica que tenha um segmentador associado, o gráfico será atualizado automaticamente para refletir suas seleções de segmentação.

P: Posso alterar a ordem de classificação dos itens dentro de um segmentador?

R: Sim. Clique com o botão direito no segmentador e selecione Configurações de Segmentação de Dados. Na caixa de diálogo, você pode escolher a ordem de classificação crescente (A-Z) ou decrescente (Z-A), ou optar por classificar usando uma lista personalizada. Você também pode controlar se os itens excluídos dos dados de origem são mantidos na exibição do segmentador.


Veja Também

Excel 테이블 및 피벗 테이블용 슬라이서 삽입 방법 알아보기

끝없는 드롭다운 메뉴 속에서 Excel 필터를 관리하느라 지치셨나요? 더 나은 방법이 있습니다. 슬라이서(Slicers)는 번거로운 데이터 탐색 과정을 클릭 한 번으로 가능한 시각적 경험으로 바꿔주며, 선택 항목을 항상 표시하고 대시보드를 대화형으로 유지해 줍니다.

이 가이드에서는 테이블이나 피벗 테이블을 사용할 때 Excel에 슬라이서를 삽입하는 방법을 정확히 배울 수 있습니다. 전문적인 대시보드를 구축하기 위한 모범 사례를 다루고, C#을 사용하여 이 과정을 자동화하는 방법까지 보여드립니다.


Excel의 슬라이서란 무엇인가요?

슬라이서는 데이터 열의 고유 값에 해당하는 클릭 가능한 버튼으로 구성된 시각적 필터링 도구입니다. 필터 옵션을 드롭다운 메뉴 속에 숨기는 대신, 슬라이서는 워크시트에 직접 표시하므로 현재 필터 상태를 한눈에 확인할 수 있습니다.

슬라이서를 데이터를 위한 직관적인 제어판이라고 생각하세요. 버튼을 클릭하면 테이블, 피벗 테이블 또는 차트가 즉시 업데이트됩니다. 선택된 버튼은 강조 표시된 상태로 유지되므로, 사용자는 어떤 필터가 활성화되어 있는지 항상 알 수 있습니다.


슬라이서가 기존 필터보다 뛰어난 이유

기능 기존 필터 슬라이서
가시성 필터 상태가 드롭다운 메뉴 안에 숨겨짐 선택된 필터가 항상 표시됨
사용 편의성 메뉴 계층을 탐색하기 위해 여러 번 클릭 필요 클릭 한 번으로 즉시 필터링
다중 선택 번거롭고 직관적이지 않음 Ctrl 키를 누르거나 다중 선택 토글 사용
다중 데이터 소스 하나의 테이블에만 연결됨 여러 피벗 테이블과 차트를 제어 가능
대시보드 친화성 대시보드용으로 설계되지 않음 대화형 대시보드에 최적

표준 필터는 작은 화살표를 클릭하고, "모두 선택"을 해제하고, 긴 목록을 스크롤한 뒤 확인을 눌러야 합니다. 클릭을 멈추는 순간 필터링 선택 사항이 시야에서 사라져 현재 무엇이 적용되었는지 추측해야 합니다. Excel 슬라이서 도구는 모든 필터 옵션을 워크시트에 직접 배치된 명확하고 클릭 가능한 버튼으로 만들어 이 문제를 완전히 해결합니다.


슬라이서 삽입 전 필수 조건

Excel에 슬라이서를 추가하기 전에 데이터가 다음 요구 사항을 충족하는지 확인하세요:

  • Excel 테이블 또는 피벗 테이블로 서식 지정: 슬라이서는 서식이 지정되지 않은 원시 셀 범위에서는 작동하지 않습니다.
  • 지원되는 Excel 버전: 슬라이서는 Windows용 Excel 2013 이상, Mac용 Excel 2016 이상에서 사용할 수 있습니다.
  • 빈 행이나 열 없음: 데이터 세트 내에 빈 행이나 열이 있으면 Excel이 전체 데이터 범위를 잘못 해석할 수 있습니다.
  • 깔끔하고 구조화된 데이터: 모든 열에 고유하고 설명적인 헤더가 있고 데이터 서식이 일관적인지 확인하세요.

범위를 테이블로 변환하려면 데이터를 선택하고 "Ctrl + T"를 누른 다음 확인을 클릭하세요.


Excel에서 슬라이서를 추가하는 방법: 두 가지 방법

슬라이서 삽입 과정은 일반 Excel 테이블을 사용하는지, 피벗 테이블을 사용하는지에 따라 다릅니다. 두 가지 모두 다룹니다.

방법 1: Excel 테이블에 슬라이서 삽입

  • Excel 테이블 내부의 아무 곳이나 클릭합니다.
  • 리본 메뉴에서 테이블 디자인 탭으로 이동합니다.
  • 도구 그룹에서 슬라이서 삽입 버튼을 클릭합니다.

테이블 디자인 탭 아래의 슬라이서 삽입 버튼.

  • 팝업 대화 상자에서 슬라이서로 사용할 열(예: 지역, 제품, 카테고리)의 확인란을 선택합니다.
  • 확인을 클릭합니다.

테이블 열이 나열된 Excel 슬라이서 삽입 대화 상자.

Excel이 워크시트에 직접 슬라이서 개체를 배치합니다. 각 슬라이서는 해당 필드의 모든 고유 항목에 대한 버튼을 표시합니다. 슬라이서 내의 버튼을 클릭하면 테이블이 즉시 필터링됩니다.

세 개의 슬라이서가 포함된 판매 데이터 테이블이 있는 Excel 워크시트.

방법 2: 피벗 테이블에 슬라이서 삽입

  • 피벗 테이블 내부의 아무 셀이나 클릭합니다.
  • 피벗 테이블 분석 탭(버전에 따라 분석 탭)으로 이동합니다.
  • 필터 그룹에서 슬라이서 삽입을 클릭합니다.

피벗 테이블 분석 탭 아래의 슬라이서 삽입 버튼.

  • 슬라이서 삽입 대화 상자에서 필터링할 필드(예: 제품)의 확인란을 선택합니다.
  • 확인을 클릭합니다.

슬라이서가 시트에 나타나며 피벗 테이블 결과를 동적으로 업데이트합니다. 대시보드 레이아웃에 맞게 이동, 크기 조정 및 서식을 지정할 수 있습니다.

제품별 총 수익을 요약하고 제품 슬라이서와 연결된 피벗 테이블.


고급: C#을 사용하여 Excel에서 프로그래밍 방식으로 슬라이서 만들기

수동 방법은 일회성 작업에는 완벽하지만, 수백 개의 Excel 파일에 프로그래밍 방식으로 슬라이서를 추가해야 할 수도 있습니다. 이때 Free Spire.XLS for .NET이 유용합니다. 이 무료 라이브러리를 사용하면 Microsoft Office를 설치하지 않고도 Excel 파일을 생성, 읽기 및 수정할 수 있으며, Excel 테이블에 슬라이서를 삽입하는 기능을 완벽하게 지원합니다.

C# 코드: Excel 테이블에 슬라이서 추가하기

아래는 기존 Excel 파일을 로드하고, 첫 번째 워크시트의 첫 번째 테이블을 가져와 두 개의 서로 다른 열에 대해 두 개의 슬라이서를 삽입하는 전체 C# 예제입니다. 그런 다음 각 슬라이서에 이름과 기본 제공 스타일을 설정하고 결과를 새 .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 테이블 개체가 필요합니다. 슬라이서 삽입 API를 호출하기 전에 항상 Excel 테이블을 생성하고 구성하세요.

결과:

Free Spire.XLS 라이브러리를 사용하여 C#으로 Excel 슬라이서 두 개 삽입

프로그래밍 방식 슬라이서 삽입을 위한 추가 팁

  • 다중 테이블: 워크시트에 테이블이 여러 개 있는 경우 worksheet.ListObjects[index]를 통해 액세스할 수 있습니다.
  • 피벗 테이블 슬라이서: Free Spire.XLS는 worksheet.Slicers.Add(IPivotTable, string, int)를 사용하여 피벗 테이블에 슬라이서를 추가하는 기능도 지원합니다.
  • 저장 형식: 슬라이서가 올바르게 유지되도록 ExcelVersion.Version2013 또는 Version2016을 사용하세요.
  • 성능: 여러 파일을 처리할 때는 각 파일에 대해 새 Workbook 인스턴스를 생성하고 처리 후 즉시 Dispose()를 호출하여 메모리 누수를 방지하세요.

삽입된 Excel 슬라이서 사용 방법

슬라이서 사용은 매우 간단합니다:

  • 단일 선택: 버튼을 클릭하여 해당 값으로 데이터를 필터링합니다.
  • 다중 선택: Ctrl 키를 누른 상태에서 여러 버튼을 클릭하거나, 슬라이서 패널 상단의 다중 선택 토글을 클릭합니다.
  • 필터 지우기: 슬라이서 오른쪽 상단 모서리에 있는 필터 지우기 버튼(X 표시가 있는 깔때기 아이콘)을 클릭합니다.

다중 선택, 필터 지우기 버튼 및 필터 값의 수직 목록을 보여주는 Excel 슬라이서 패널.


Excel 슬라이서 사용을 위한 모범 사례

  1. 슬라이서를 대시보드 상단이나 측면에 그룹화하고 정렬해 두세요.
  2. 뷰어가 각 슬라이서가 무엇을 필터링하는지 이해할 수 있도록 설명적인 캡션을 사용하세요.
  3. 슬라이서 개수를 제한하세요. 보통 3~5개가 복잡하지 않으면서 충분한 대화형 기능을 제공합니다.
  4. 더 쉽게 관리할 수 있도록 선택 창(Alt + F10)에서 슬라이서 이름을 지정하세요.
  5. 사용자가 스크롤할 때 슬라이서가 제자리에 있도록 위치를 잠그세요(마우스 오른쪽 버튼 클릭 → 크기 및 속성 → 속성 → "셀과 함께 이동하거나 크기가 변하지 않음" 체크).
  6. 자동화의 경우, 슬라이서 호환성을 보장하기 위해 항상 ExcelVersion.Version2016 이상을 대상으로 하세요.

최종 생각

Excel에 슬라이서를 추가하는 것은 보고서나 대시보드를 구축하는 모든 사람에게 가장 영향력 있는 기술 중 하나입니다. 일반 사용자에게는 필터링을 직관적이고 투명하며 대시보드에 적합하게 만들어 중첩된 드롭다운 메뉴의 번거로움을 없애줍니다. 개발자에게는 프로그래밍 방식의 슬라이서 API를 통해 엔터프라이즈 규모에서 대화형 통합 문서를 확장 가능하고 자동화된 방식으로 생성할 수 있게 합니다.

청중을 혼란스럽게 하는 정적인 스프레드시트에 안주하지 마세요. 오늘부터 Excel 슬라이서를 사용하여 데이터의 잠재력을 최대한 활용하고, 평범한 테이블을 정보를 제공하고 깊은 인상을 남기는 강력한 대화형 의사결정 도구로 바꿔보세요.


자주 묻는 질문 (FAQs)

Q: 하나의 슬라이서를 여러 피벗 테이블에 연결할 수 있나요?

A: 네. 슬라이서를 마우스 오른쪽 버튼으로 클릭 → 보고서 연결 → 제어하려는 모든 피벗 테이블을 선택하세요.

Q: 슬라이서 색상을 변경할 수 있나요?

A: 물론입니다. 슬라이서 도구 → 옵션 탭을 사용하여 기본 제공 스타일을 적용하거나 사용자 지정 서식을 만드세요.

Q: 슬라이서가 Excel 차트와 작동하나요?

A: 네. 차트가 연결된 슬라이서가 있는 테이블이나 피벗 테이블에 연결되어 있으면, 차트가 슬라이서 선택 사항을 반영하여 자동으로 업데이트됩니다.

Q: 슬라이서 내 항목의 정렬 순서를 변경할 수 있나요?

A: 네. 슬라이서를 마우스 오른쪽 버튼으로 클릭하고 슬라이서 설정을 선택하세요. 대화 상자에서 오름차순(A-Z) 또는 내림차순(Z-A) 정렬 순서를 선택하거나 사용자 지정 목록을 사용하여 정렬할 수 있습니다. 또한 소스 데이터에서 삭제된 항목을 슬라이서 표시에 유지할지 여부도 제어할 수 있습니다.


참고 항목

Scopri come inserire slicer per tabelle Excel e tabelle pivot

Stanco di perdere traccia dei tuoi filtri Excel all'interno di infiniti menu a discesa? Esiste un modo migliore. Gli Slicer (filtri dei dati) trasformano la noiosa esplorazione dei dati in un'esperienza visiva con un solo clic, mantenendo le tue selezioni visibili e le tue dashboard interattive.

In questa guida, imparerai esattamente come inserire gli Slicer in Excel, sia che tu stia lavorando con tabelle o tabelle pivot. Tratteremo le best practice per creare dashboard professionali e ti mostreremo persino come automatizzare il processo con C#.


Cos'è uno Slicer in Excel?

Uno Slicer è uno strumento di filtraggio visivo composto da pulsanti cliccabili che corrispondono a valori univoci in una colonna di dati. Invece di nascondere le opzioni di filtro all'interno di menu a discesa, gli Slicer le visualizzano direttamente sul foglio di lavoro, rendendo lo stato attuale del filtro visibile a colpo d'occhio.

Pensa agli Slicer come a un pannello di controllo intuitivo per i tuoi dati. Fai clic su un pulsante e la tua tabella, tabella pivot o grafico si aggiornerà istantaneamente. I pulsanti selezionati rimangono evidenziati, così tu e qualsiasi altro utente potrete sempre vedere quali filtri sono attivi.


Perché gli Slicer sono superiori ai filtri tradizionali

Funzionalità Filtri tradizionali Slicer
Visibilità Lo stato del filtro è nascosto nei menu a discesa I filtri selezionati sono sempre visibili
Facilità d'uso Richiede più clic per navigare tra i livelli del menu Selezione con un clic per un filtraggio istantaneo
Selezione multipla Macchinosa e poco intuitiva Tieni premuto Ctrl o usa l'interruttore di selezione multipla
Origini dati multiple Legato a una sola tabella Può controllare più tabelle pivot e grafici
Adatto alle dashboard Non progettato per le dashboard Perfetto per dashboard interattive

I filtri standard ti costringono a fare clic su una piccola freccia, deselezionare "Seleziona tutto", scorrere un lungo elenco e fare clic su OK. Nel momento in cui fai clic altrove, le tue scelte di filtraggio scompaiono dalla vista, lasciandoti nel dubbio su cosa sia attualmente applicato. Lo strumento Slicer di Excel risolve completamente questo problema rendendo ogni opzione di filtro un pulsante chiaro e cliccabile che si trova direttamente sul tuo foglio di lavoro.


Prerequisiti prima di inserire gli Slicer

Prima di aggiungere Slicer in Excel, assicurati che i tuoi dati soddisfino questi requisiti:

  • Formattato come tabella Excel o tabella pivot: Gli Slicer non funzionano con intervalli di celle non formattati.
  • Versione di Excel supportata: Gli Slicer sono disponibili in Excel 2013 e versioni successive per Windows, e in Excel 2016 e versioni successive per Mac.
  • Nessuna riga o colonna vuota: Righe o colonne vuote all'interno del set di dati possono causare un'errata interpretazione dell'intero intervallo di dati da parte di Excel.
  • Dati puliti e strutturati: Assicurati che ogni colonna abbia un'intestazione univoca e descrittiva e una formattazione dei dati coerente.

Per convertire un intervallo in una tabella, seleziona i tuoi dati e premi "Ctrl + T", quindi fai clic su OK.


Come aggiungere Slicer in Excel: due metodi

Il processo per inserire gli Slicer dipende dal fatto che tu stia lavorando con una normale tabella Excel o una tabella pivot. Vedremo entrambi i casi.

Metodo 1: Inserire Slicer in una tabella Excel

  • Fai clic in un punto qualsiasi all'interno della tua tabella Excel.
  • Vai alla scheda Progettazione tabella sulla barra multifunzione.
  • Fai clic sul pulsante Inserisci Slicer nel gruppo Strumenti.

Il pulsante Inserisci Slicer nella scheda Progettazione tabella.

  • Nella finestra di dialogo che appare, seleziona le caselle per le colonne che desideri utilizzare come Slicer (ad esempio, Regione, Prodotto, Categoria).
  • Fai clic su OK.

Finestra di dialogo Inserisci Slicer di Excel con l'elenco delle colonne della tabella.

Excel posizionerà gli oggetti Slicer direttamente sul tuo foglio di lavoro. Ogni Slicer visualizza i pulsanti per tutti gli elementi univoci nel rispettivo campo. Fai clic su qualsiasi pulsante all'interno di uno Slicer per filtrare la tabella istantaneamente.

Foglio di lavoro Excel contenente una tabella di dati di vendita con tre Slicer.

Metodo 2: Inserire Slicer in una tabella pivot

  • Fai clic su una cella qualsiasi all'interno della tua tabella pivot.
  • Vai alla scheda Analizza tabella pivot (o scheda Analizza, a seconda della versione).
  • Fai clic su Inserisci Slicer nel gruppo Filtro.

Il pulsante Inserisci Slicer nella scheda Analizza tabella pivot.

  • Nella finestra di dialogo Inserisci Slicer, seleziona le caselle per i campi in base ai quali desideri filtrare (ad esempio, Prodotto).
  • Fai clic su OK.

Gli Slicer appaiono sul tuo foglio e aggiornano dinamicamente i risultati della tabella pivot. Puoi spostarli, ridimensionarli e formattarli per adattarli al layout della tua dashboard.

Una tabella pivot che riassume il fatturato totale per prodotto abbinata a uno Slicer Prodotto.


Avanzato: Creare Slicer in Excel a livello programmatico con C#

Sebbene i metodi manuali siano perfetti per attività singole, potresti dover aggiungere Slicer a centinaia di file Excel in modo programmatico. È qui che entra in gioco Free Spire.XLS for .NET. Questa libreria gratuita ti consente di creare, leggere e modificare file Excel senza che Microsoft Office sia installato, e supporta pienamente l'inserimento di Slicer nelle tabelle Excel.

Codice C#: Aggiungere Slicer a una tabella Excel

Di seguito è riportato un esempio C# completo che carica un file Excel esistente, recupera la prima tabella nel primo foglio di lavoro e inserisce due Slicer per due colonne diverse. Imposta quindi un nome e uno stile predefinito per ogni Slicer e salva il risultato come nuovo file .xlsx.

using Spire.Xls;
using Spire.Xls.Core;

namespace AddSlicerToTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Carica un file Excel
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("sampleData.xlsx");

            // Ottieni il primo foglio di lavoro
            Worksheet worksheet = workbook.Worksheets[0];

            // Ottieni la prima tabella nel foglio di lavoro
            IListObject table = worksheet.ListObjects[0];

            // Aggiungi 2 Slicer
            // Parametri: tabella, posizione (riferimento cella), indice colonna (base 0)
            int slicer1 = worksheet.Slicers.Add(table, "G3", 1);
            int slicer2 = worksheet.Slicers.Add(table, "H5", 2);

            // Imposta nome e stile per lo Slicer
            worksheet.Slicers[slicer1].Name = "Regione";
            worksheet.Slicers[slicer1].StyleType = SlicerStyleType.SlicerStyleLight1;
            worksheet.Slicers[slicer2].Name = "Categoria";
            worksheet.Slicers[slicer2].StyleType = SlicerStyleType.SlicerStyleDark1;

            // Salva il file risultante
            workbook.SaveToFile("AddSlicers.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}

Come funziona l'API Slicer

Il metodo principale è Slicers.Add() con la seguente firma:

int Add(IListObject table, string destCellName, int index);
  • table: L'IListObject di origine (tabella Excel) a cui è associato lo Slicer
  • destCellName: Indirizzo della cella in alto a sinistra dove viene posizionato lo Slicer (ad esempio, "G3")
  • index: Indice basato su 0 della colonna all'interno della tabella da utilizzare come valori di filtro.

Nota: Gli Slicer richiedono un oggetto Tabella Excel strutturato. Crea e configura sempre la tua tabella Excel prima di chiamare l'API di inserimento Slicer.

Risultato:

Inserisci due Slicer Excel usando C# con la libreria Free Spire.XLS

Suggerimenti aggiuntivi per l'inserimento programmatico di Slicer

  • Tabelle multiple: Se il tuo foglio di lavoro ha più di una tabella, puoi accedervi tramite worksheet.ListObjects[index].
  • Slicer per tabelle pivot: Free Spire.XLS supporta anche l'aggiunta di Slicer alle tabelle pivot utilizzando worksheet.Slicers.Add(IPivotTable, string, int).
  • Formati di salvataggio: Usa ExcelVersion.Version2013 o Version2016 per assicurarti che gli Slicer vengano conservati correttamente.
  • Prestazioni: Quando elabori più file, crea una nuova istanza di Workbook per ogni file e chiama Dispose() subito dopo l'elaborazione per evitare perdite di memoria.

Come utilizzare gli Slicer di Excel una volta inseriti

Utilizzare gli Slicer è straordinariamente semplice:

  • Selezione singola: Fai clic su un pulsante qualsiasi per filtrare i tuoi dati su quel valore
  • Selezione multipla: Tieni premuto Ctrl mentre fai clic su più pulsanti, oppure fai clic sull'interruttore Selezione multipla nella parte superiore del pannello Slicer
  • Cancellare un filtro: Fai clic sul pulsante Cancella filtro (l'icona a imbuto con una X) nell'angolo in alto a destra dello Slicer

Un pannello Slicer di Excel che mostra la selezione multipla, il pulsante Cancella filtro e un elenco verticale di valori di filtro.


Best practice per gli Slicer di Excel

  1. Mantieni gli Slicer raggruppati e allineati nella parte superiore o laterale della tua dashboard.
  2. Usa didascalie descrittive in modo che gli spettatori capiscano cosa filtra ogni Slicer.
  3. Limita il numero di Slicer: 3-5 solitamente offrono abbastanza interattività senza creare confusione.
  4. Nomina i tuoi Slicer nel riquadro di selezione (Alt + F10) per una gestione più semplice.
  5. Blocca le posizioni degli Slicer (tasto destro → Dimensioni e proprietà → Proprietà → seleziona "Non spostare o ridimensionare con le celle") in modo che rimangano al loro posto quando gli utenti scorrono.
  6. Per l'automazione, punta sempre a ExcelVersion.Version2016 o superiore per garantire la compatibilità degli Slicer.

Considerazioni finali

Aggiungere Slicer in Excel è una delle competenze di maggiore impatto per chiunque crei report o dashboard. Per gli utenti quotidiani, rendono il filtraggio intuitivo, trasparente e pronto per la dashboard, eliminando l'attrito dei menu a discesa nidificati. Per gli sviluppatori, le API Slicer programmatiche consentono la generazione scalabile e automatizzata di cartelle di lavoro interattive su scala aziendale.

Non accontentarti di fogli di calcolo statici che confondono il tuo pubblico. Inizia a utilizzare gli Slicer di Excel oggi stesso per sbloccare tutto il potenziale dei tuoi dati, trasformando tabelle ordinarie in potenti strumenti interattivi per il processo decisionale che informano e colpiscono.


Domande frequenti (FAQ)

D: Posso collegare uno Slicer a più tabelle pivot?

R: Sì. Fai clic con il tasto destro sullo Slicer → Connessioni report → seleziona tutte le tabelle pivot che desideri controllare.

D: Posso cambiare i colori dello Slicer?

R: Assolutamente sì. Usa la scheda Strumenti Slicer → Opzioni per applicare stili predefiniti o creare una formattazione personalizzata.

D: Gli Slicer funzionano con i grafici Excel?

R: Sì. Se un grafico è collegato a una tabella o tabella pivot che ha uno Slicer associato, il grafico si aggiornerà automaticamente per riflettere le tue selezioni nello Slicer.

D: Posso modificare l'ordinamento degli elementi all'interno di uno Slicer?

R: Sì. Fai clic con il tasto destro sullo Slicer e seleziona Impostazioni Slicer. Nella finestra di dialogo, puoi scegliere l'ordinamento crescente (A-Z) o decrescente (Z-A), oppure scegliere di ordinare utilizzando un elenco personalizzato. Puoi anche controllare se gli elementi eliminati dai dati di origine vengono conservati nella visualizzazione dello Slicer.


Vedi anche

Découvrez comment insérer des segments pour les tableaux et tableaux croisés dynamiques Excel

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 ?

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.

Le bouton Insérer un segment sous l'onglet Création de tableau.

  • 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.

Boîte de dialogue Insérer des segments d'Excel listant les colonnes du tableau.

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.

Feuille de calcul Excel contenant un tableau de données de ventes avec trois segments.

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.

Le bouton Insérer un segment sous l'onglet Analyse du tableau croisé dynamique.

  • 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.

Un tableau croisé dynamique résumant le revenu total par produit associé à un segment Produit.


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 :

Insérer deux segments Excel en utilisant C# avec la bibliothèque Free Spire.XLS

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.Version2013 ou Version2016 pour 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

Un panneau de segment Excel montrant la sélection multiple, le bouton Effacer le filtre et une liste verticale de valeurs de filtre.


Meilleures pratiques pour les segments Excel

  1. Gardez les segments regroupés et alignés en haut ou sur le côté de votre tableau de bord.
  2. Utilisez des légendes descriptives pour que les utilisateurs comprennent ce que chaque segment filtre.
  3. Limitez le nombre de segments — 3 à 5 offrent généralement suffisamment d'interactivité sans encombrer.
  4. Nommez vos segments dans le volet de sélection (Alt + F10) pour une gestion plus facile.
  5. 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.
  6. 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

Explore cómo insertar segmentadores para tablas y tablas dinámicas de Excel

¿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?

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.

El botón Insertar segmentación de datos bajo la pestaña Diseño de tabla.

  • 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.

Cuadro de diálogo Insertar segmentación de datos de Excel que enumera las columnas de la tabla.

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.

Hoja de cálculo de Excel que contiene una tabla de datos de ventas con tres segmentadores.

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.

El botón Insertar segmentación de datos bajo la pestaña Analizar tabla dinámica.

  • 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.

Una tabla dinámica que resume los ingresos totales por producto junto con un segmentador de Producto.


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:

Insertar dos segmentadores de Excel usando C# con la biblioteca Free Spire.XLS

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.Version2013 o Version2016 para 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

Un panel de segmentador de Excel que muestra el botón de Selección múltiple, Borrar filtro y una lista vertical de valores de filtro.


Mejores prácticas para los segmentadores de Excel

  1. Mantenga los segmentadores agrupados y alineados en la parte superior o lateral de su panel.
  2. Use títulos descriptivos para que los espectadores entiendan qué filtra cada segmentador.
  3. Limite el número de segmentadores: 3-5 suelen dar suficiente interactividad sin saturar.
  4. Nombre sus segmentadores en el Panel de selección (Alt + F10) para una gestión más fácil.
  5. 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.
  6. 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

Erfahren Sie, wie Sie Datenschnitte für Excel-Tabellen und Pivot-Tabellen einfügen

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?

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.

Die Schaltfläche 'Datenschnitt einfügen' unter der Registerkarte 'Tabellenentwurf'.

  • 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.

Dialogfeld 'Datenschnitte einfügen' mit Auflistung der Tabellenspalten.

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.

Excel-Arbeitsblatt mit einer Verkaufsdatentabelle und drei Datenschnitten.

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.

Die Schaltfläche 'Datenschnitt einfügen' unter der Registerkarte 'PivotTable-Analyse'.

  • 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.

Eine Pivot-Tabelle, die den Gesamtumsatz nach Produkt zusammenfasst, kombiniert mit einem Produktdatenschnitt.


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:

Zwei Excel-Datenschnitte mit C# und der Free Spire.XLS-Bibliothek einfügen

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.Version2013 oder Version2016, 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

Ein Excel-Datenschnitt-Bereich mit Mehrfachauswahl, Filter löschen-Schaltfläche und einer vertikalen Liste von Filterwerten.


Best Practices für Excel-Datenschnitte

  1. Halten Sie Datenschnitte gruppiert und ausgerichtet am oberen oder seitlichen Rand Ihres Dashboards.
  2. Verwenden Sie beschreibende Beschriftungen, damit die Betrachter verstehen, was jeder Datenschnitt filtert.
  3. Begrenzen Sie die Anzahl der Datenschnitte – 3–5 bieten normalerweise genug Interaktivität, ohne das Bild zu überladen.
  4. Benennen Sie Ihre Datenschnitte im Auswahlbereich (Alt + F10) für eine einfachere Verwaltung.
  5. 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.
  6. 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

Узнайте, как вставлять срезы для таблиц Excel и сводных таблиц

Устали теряться в бесконечных выпадающих списках фильтров Excel? Есть решение получше. Срезы (Slicers) превращают утомительный поиск данных в визуальный процесс в один клик, позволяя всегда видеть выбранные параметры и делая ваши отчеты интерактивными.

В этом руководстве вы узнаете, как именно вставлять срезы в Excel, работаете ли вы с обычными таблицами или сводными таблицами (PivotTables). Мы рассмотрим лучшие практики создания профессиональных дашбордов и даже покажем, как автоматизировать этот процесс с помощью C#.


Что такое срез (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 со списком столбцов таблицы.

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

Лист 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 для вставки срезов.

Результат:

Вставка двух срезов Excel с помощью C# и библиотеки Free Spire.XLS

Дополнительные советы по программной вставке срезов

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

Как использовать срезы Excel после их добавления

Использовать срезы удивительно просто:

  • Одиночный выбор: Нажмите любую кнопку, чтобы отфильтровать данные по этому значению.
  • Множественный выбор: Удерживайте Ctrl при нажатии нескольких кнопок или нажмите переключатель Мультивыбор в верхней части панели среза.
  • Очистка фильтра: Нажмите кнопку Очистить фильтр (значок воронки с крестиком) в правом верхнем углу среза.

Панель среза Excel с кнопками мультивыбора, очистки фильтра и вертикальным списком значений.


Рекомендации по работе со срезами в Excel

  1. Держите срезы сгруппированными и выровненными в верхней или боковой части вашего дашборда.
  2. Используйте описательные заголовки, чтобы зрители понимали, за что отвечает каждый срез.
  3. Ограничьте количество срезов — 3–5 штук обычно достаточно для интерактивности без перегрузки интерфейса.
  4. Давайте срезам понятные имена в области выделения (Alt + F10) для упрощения управления.
  5. Закрепляйте положение срезов (правой кнопкой мыши → Размер и свойства → Свойства → установите «Не перемещать и не изменять размеры вместе с ячейками»), чтобы они оставались на месте при прокрутке.
  6. Для автоматизации всегда ориентируйтесь на ExcelVersion.Version2016 или выше для обеспечения совместимости.

Заключение

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

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


Часто задаваемые вопросы (FAQ)

В: Можно ли подключить один срез к нескольким сводным таблицам?

О: Да. Нажмите правой кнопкой мыши на срез → Подключения к отчету → выберите все сводные таблицы, которыми хотите управлять.

В: Можно ли изменить цвета среза?

О: Конечно. Используйте вкладку «Параметры» в разделе «Работа со срезами», чтобы применить встроенные стили или создать собственное форматирование.

В: Работают ли срезы с диаграммами Excel?

О: Да. Если диаграмма связана с таблицей или сводной таблицей, у которой есть связанный срез, диаграмма будет автоматически обновляться в соответствии с вашим выбором в срезе.

В: Можно ли изменить порядок сортировки элементов внутри среза?

О: Да. Нажмите правой кнопкой мыши на срез и выберите «Параметры среза». В диалоговом окне вы можете выбрать сортировку по возрастанию (А-Я) или по убыванию (Я-А), либо выбрать сортировку по настраиваемому списку. Вы также можете управлять тем, будут ли элементы, удаленные из исходных данных, сохраняться в отображении среза.


Смотрите также

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 Original CSV data 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 Original PDF data PDF table extraction result


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

Configure it in code:

AIOptions options = new AIOptions();
options.SpireToken = key;

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 Original invoice PDF Extracted and exported Excel 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

Configure it in code:

AIOptions options = new AIOptions();
options.SpireToken = key;

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 Workbook object and load an existing Excel file.
  • Call the workbook's SaveToFile() method, specifying the output filename and the FileFormat.ODS file 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

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 Workbook object and load the ODS file via the LoadFromFile() 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

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.

Page 1 of 269