Knowledgebase (2613)
Children categories
How to Filter Excel Pivot Tables with Python: Step-by-Step Guide
2025-05-16 10:01:44 Written by Administrator
Introduction
Pivot Tables in Excel are versatile tools that enable efficient data summarization and analysis. They allow users to explore data, uncover insights, and generate reports dynamically. One of the most powerful features of Pivot Tables is filtering, which lets users focus on specific data subsets without altering the original data structure.
What This Tutorial Covers
This tutorial provides a detailed, step-by-step guide on how to programmatically apply various types of filters to a Pivot Table in Excel using Python with the Spire.XLS for Python library. It covers the following topics:
- Benefits of Filtering Data in Pivot Tables
- Install Python Excel Library – Spire.XLS for Python
- Add Report Filter to Pivot Table
- Apply Row Field Filter in Pivot Table
- Apply Column Field Filter in Pivot Table
- FAQs
- Conclusion
Benefits of Filtering Data in Pivot Tables
Filtering is an essential feature of Pivot Tables that provides the following benefits:
- Enhanced Data Analysis: Quickly focus on specific segments or categories of your data to draw meaningful insights.
- Dynamic Data Updates: Filters automatically adjust to reflect changes when the underlying data is refreshed, keeping your analysis accurate.
- Improved Data Organization: Display only relevant data in your reports without altering or deleting the original dataset, preserving data integrity.
Install Python Excel Library – Spire.XLS for Python
Before working with Pivot Tables in Excel using Python, ensure the Spire.XLS for Python library is installed. The quickest way to do this is using pip, Python’s package manager. Simply run the following command in your terminal or command prompt:
pip install spire.xls
Once installed, you’re ready to start automating Pivot Table filtering in your Python projects.
Add Report Filter to Pivot Table
A report filter allows you to filter the entire Pivot Table based on a particular field and value. This type of filter is useful when you want to display data for a specific category or item globally across the Pivot Table, without changing the layout.
Steps to Add a Report Filter
- Initialize the Workbook: Create a Workbook object to manage your Excel file.
- Load the Excel File: Use Workbook.LoadFromFile() to load an existing file containing a Pivot Table.
- Access the Worksheet: Use Workbook.Worksheets[] to select the desired worksheet.
- Locate the Pivot Table: Use Worksheet.PivotTables[] to access the specific Pivot Table.
- Define the Report Filter: Create a PivotReportFilter object specifying the field to filter.
- Apply the Report Filter: Add the filter to the Pivot Table using XlsPivotTable.ReportFilters.Add().
- Save the Updated File: Use Workbook.SaveToFile() to save your changes.
Code Example
- Python
from spire.xls import *
# Create an object of the Workbook class
workbook = Workbook()
# Load an existing Excel file containing a Pivot Table
workbook.LoadFromFile("Sample.xlsx")
# Access the first worksheet
sheet = workbook.Worksheets[0]
# Access the first Pivot Table in the worksheet
pt = sheet.PivotTables[0]
# Create a report filter for the field "Product"
reportFilter = PivotReportFilter("Product", True)
# Add the report filter to the pivot table
pt.ReportFilters.Add(reportFilter)
# Save the updated workbook to a new file
workbook.SaveToFile("AddReportFilter.xlsx", FileFormat.Version2016)
workbook.Dispose()

Apply Row Field Filter in Pivot Table
Row field filters allow you to filter data displayed in the row fields of an Excel Pivot Table. These filters can be based on labels (specific text values) or values (numeric criteria).
Steps to Add a Row Field Filter
- Initialize the Workbook: Create a Workbook object to manage the Excel file.
- Load the Excel File: Use Workbook.LoadFromFile() to load your target file containing a Pivot Table.
- Access the Worksheet: Select the desired worksheet using Workbook.Worksheets[].
- Locate the Pivot Table: Access the specific Pivot Table using Worksheet.PivotTables[].
- Add a Row Field Filter: Add a label filter or value filter using
XlsPivotTable.RowFields[].AddLabelFilter() or
XlsPivotTable.RowFields[].AddValueFilter().
- Calculate Pivot Table Data: Use XlsPivotTable.CalculateData() to calculate the pivot table data.
- Save the Updated File: Save your changes using Workbook.SaveToFile().
Code Example
- Python
from spire.xls import *
# Create an object of the Workbook class
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Sample.xlsx")
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Get the first pivot table
pt = sheet.PivotTables[0]
# Add a value filter to the first row field in the pivot table
pt.RowFields[0].AddValueFilter(PivotValueFilterType.GreaterThan, pt.DataFields[0], Int32(5000), None)
# Or add a label filter to the first row field in the pivot table
# pt.RowFields[0].AddLabelFilter(PivotLabelFilterType.Equal, "Mike", None)
# Calculate the pivot table data
pt.CalculateData()
# Save the resulting file
workbook.SaveToFile("AddRowFieldFilter.xlsx", FileFormat.Version2016)
workbook.Dispose()

Apply Column Field Filter in Pivot Table
Column field filters in Excel Pivot Tables allow you to filter data displayed in the column fields. Similar to row field filters, column field filters can be based on labels (text values) or values (numeric criteria).
Steps to Add Column Field Filter
- Initialize the Workbook: Create a Workbook object to manage your Excel file.
- Load the Excel File: Use Workbook.LoadFromFile() to open your file containing a Pivot Table.
- Access the Worksheet: Select the target worksheet using Workbook.Worksheets[].
- Locate the Pivot Table: Use Worksheet.PivotTables[] to access the desired Pivot Table.
- Add a Column Field Filter: Add a label filter or value filter using
XlsPivotTable.ColumnFields[].AddLabelFilter() or
XlsPivotTable.ColumnFields[].AddValueFilter().
- Calculate Pivot Table Data: Use XlsPivotTable.CalculateData() to calculate the Pivot Table data.
- Save the Updated File: Save your changes using Workbook.SaveToFile().
Code Example
- Python
from spire.xls import *
# Create an object of the Workbook class
workbook = Workbook()
# Load the Excel file
workbook.LoadFromFile("Sample.xlsx")
# Access the first worksheet
sheet = workbook.Worksheets[0]
# Access the first Pivot Table
pt = sheet.PivotTables[0]
# Add a label filter to the first column field
pt.ColumnFields[0].AddLabelFilter(PivotLabelFilterType.Equal, String("Laptop"), None)
# # Or add a value filter to the first column field
# pt.ColumnFields[0].AddValueFilter(PivotValueFilterType.Between, pt.DataFields[0], Int32(5000), Int32(10000))
# Calculate the pivot table data
pt.CalculateData()
# Save the updated workbook
workbook.SaveToFile("AddColumnFieldFilter.xlsx", FileFormat.Version2016)
workbook.Dispose()

Conclusion
Filtering Pivot Tables in Excel is crucial for effective data analysis, allowing users to zoom in on relevant information without disrupting the table’s structure. Using Spire.XLS for Python, developers can easily automate adding, modifying, and managing filters on Pivot Tables programmatically. This tutorial covered the primary filter types—report filters, row field filters, and column field filters—with detailed code examples to help you get started quickly.
FAQs
Q: Can I add multiple filters to the same Pivot Table?
A: Yes, you can add multiple report filters, row filters, and column filters simultaneously to customize your data views with Spire.XLS.
Q: Do filters update automatically if the source data changes?
A: Yes, after refreshing the Pivot Table or recalculating with CalculateData(), filters will reflect the latest data.
Q: Can I filter based on custom conditions?
A: Spire.XLS supports many filter types including label filters (equals, begins with, contains) and value filters (greater than, less than, between).
Q: Is it possible to remove filters programmatically?
A: Yes, you can remove filters by clearing or resetting the respective filter collections or fields.
Get a Free License
To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.
Extract Background Images from PowerPoint Presentations using C# .NET
2025-05-16 09:01:16 Written by Administrator
PowerPoint presentations often contain background images that enhance the visual appeal of slides. Extracting these background images can be crucial for designers and content managers who wish to reuse, analyze, or archive slide visuals independently of the slide content.
This guide provides a clear, step-by-step approach to extracting background images from PowerPoint presentations in .NET using C# and the Spire.Presentation for .NET library.
Table of Contents
- Why Extract Background Images from PowerPoint
- Install .NET PowerPoint Library – Spire.Presentation for .NET
- Extract Background Images from PowerPoint in .NET using C#
- FAQs
- Conclusion
Why Extract Background Images from PowerPoint
Extracting background images from PowerPoint provides several key benefits:
- Reuse Designs: Repurpose background images in other presentations or design projects.
- Analyze Slides: Review and understand slide designs by examining background images separately.
- Archive Visuals: Store background images for documentation, backup, or future use.
Install .NET PowerPoint Library – Spire.Presentation for .NET
Spire.Presentation for .NET is a robust .NET PowerPoint library that enables developers to create, manipulate, and convert PowerPoint presentations without the need for Microsoft PowerPoint.
Key Features of Spire.Presentation for .NET
Here are some key features of Spire.Presentation for .NET:
- Create and edit PowerPoint presentations.
- Convert PowerPoint to other formats such as PDF, Images, HTML, Markdown, and XPS.
- Secure PowerPoint presentations
- Merge/split PowerPoint presentations.
- Slides management, including adding/removing slides, setting/extracting/removing backgrounds, and more.
- Image/shape/chart/smartart insertion and manipulation.
- Animate text/shapes.
Install Spire.Presentation for .NET
Before starting the background image extraction process, you will need to install Spire.Presentation for .NET into your C# project using one of the following methods:
Option1. Install via NuGet (Recommended)
Install-Package Spire.Presentation
Option 2: Manually Add DLLs to Your Project
- Download the Spire.Presentation package and extract the files.
- In Visual Studio, right-click References > Add Reference > Browse, then select the appropriate Spire.Presentation.dll based on your target framework.
Extract Background Images from PowerPoint in .NET using C#
Background images in PowerPoint can be applied directly to individual slides or inherited from slide masters. This section demonstrates how to extract both types of background images using Spire.Presentation.
Extract Background Images from Individual Slides
To extract background images from individual slides in PowerPoint, follow these steps:
- Create a Presentation object and load the presentation.
- Loop through all slides in the presentation.
- Check if the slide’s background fill type is image fill (FillFormatType.Picture).
- If yes, retrieve and save the background image.
Sample Code
- C#
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.IO;
namespace ExtractSlideBackgroundImages
{
internal class Program
{
static void Main(string[] args)
{
// Specify the input file path and output folder
string inputFile = @"example1.pptx";
string outputFolder = @"ExtractedBackgrounds\Slides";
// Load the PowerPoint presentation
Presentation presentation = new Presentation();
presentation.LoadFromFile(inputFile);
// Create the output folder
Directory.CreateDirectory(outputFolder);
// Loop through all slides
for (int i = 0; i < presentation.Slides.Count; i++)
{
// Check if the slide's background fill type is image fill
var fill = presentation.Slides[i].SlideBackground.Fill;
if (fill.FillType == FillFormatType.Picture)
{
// Extract and save the background image
var image = fill.PictureFill.Picture.EmbedImage;
if (image != null)
{
string outputPath = Path.Combine(outputFolder, $"SlideBackground_{i + 1}.png");
image.Image.Save(outputPath, ImageFormat.Png);
}
}
}
}
}
}
Extract Background Images from Slide Masters
Slide masters define the design and layout of slides, including background images. To extract background images from slide masters:
- Create a Presentation object and load the presentation.
- Loop through all slide masters in the presentation.
- For each master, check if its background fill type is image fill.
- If yes, extract and save the background image.
Sample Code
- C#
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace ExtractBackgroundImages
{
internal class Program
{
static void Main(string[] args)
{
// Specify the input file path and output folder
string inputFile = @"example2.pptx";
string outputFolder = @"C:\ExtractedBackgrounds\Masters";
// Load the PowerPoint presentation
Presentation presentation = new Presentation();
presentation.LoadFromFile(inputFile);
// Create the output folder
Directory.CreateDirectory(outputFolder);
// Loop through all slide masters
for (int i = 0; i < presentation.Masters.Count; i++)
{
// Check if the slide master's background fill type is image fill
var fill = presentation.Masters[i].SlideBackground.Fill;
if (fill.FillType == FillFormatType.Picture)
{
// Extract and save the background image
var image = fill.PictureFill.Picture.EmbedImage;
if (image != null)
{
string outputPath = Path.Combine(outputFolder, $"MasterBackground_{i + 1}.png");
image.Image.Save(outputPath, ImageFormat.Png);
}
}
}
}
}
}
Conclusion
Extracting background images from PowerPoint presentations is a crucial technique for developers and designers who want to access slide visuals independently of content. By leveraging the Spire.Presentation for .NET library with C#, you can programmatically extract background images from both individual slides and slide masters with ease.
FAQs
Q: What image formats are supported for extraction?
A: Extracted images can be saved in PNG, JPEG, BMP, or other formats supported by .NET.
Q: In addition to background images, can I extract other images from PowerPoint slides?
A: Yes, you can extract other images, such as those embedded within slide content or shapes, using Spire.Presentation.
Q: Does Spire.Presentation supports extracting text from PowerPoint presentations?
A: Yes, Spire.Presentation can also extract text from slides, including text in shapes, tables, and more.
Get a Free License
To fully experience the capabilities of Spire.Presentation for .NET without any evaluation limitations, you can request a free 30-day trial license.

In data processing and management scenarios, efficiently transforming raw text (TXT) files into structured Excel spreadsheets is a common requirement. For developers who are automating reports or processing log files, converting TXT to Excel using C# streamlines data organization and analysis. This guide explores how to achieve this using Spire.XLS for .NET, a powerful library designed to handle Excel XLS or XLSX files without requiring Microsoft Office.
- Why Convert TXT to Excel Programmatically?
- How to Convert Text Files to Excel in C# (Step-by-Step Guide)
- Pro Tips for TXT to Excel Conversion
Why Convert TXT to Excel Programmatically?
Text files are simple but lack the analytical power of Excel. Key advantages of converting TXT to XLS or XLSX format include:
- Automation: Process large or recurring files without manual intervention.
- Data Structuring: Organize raw text into rows, columns, and sheets.
- Advanced Features: Leverage Excel formulas, charts, and pivot tables.
- Integration: Embed conversion feature into .NET applications or APIs.
How to Convert Text Files to Excel in C# (Step-by-Step Guide)
Install Spire.XLS for .NET
Spire.XLS for .NET is a professional Excel document processing component, provides efficient and convenient APIs that allow developers to achieve TXT to Excel conversion through simple code.
Before getting started, you can choose one of these methods to install the library:
Method 1: NuGet Package Manager
- Open your project in Visual Studio.
- Right-click on the project in the Solution Explorer and select "Manage NuGet Packages."
- Search for "Spire.XLS" and click "Install".
Method 2: Package Manager Console
- Go to "Tools > NuGet Package Manager > Package Manager Console."
- Run the following command in the console:
PM> Install-Package Spire.XLS
Method 3: Manual Installation with DLL Files
- Visit the Spire.XLS Download Page and get the latest version.
- Extract the files and then add the Spire.Xls.dll to your project.
Import a Text File into Excel Using C#
Follow the below steps to write the data in a txt file into an Excel worksheet:
- Read TXT File: use the File.ReadAllLines() method to read all lines in a text file and returns them as an array of strings.
- Parse each line:
- Use the string.Trim() method to remove the leading/trailing whitespaces.
- Use the string.Split() method to split the data based on specified delimiters.
- Add the split text data to a list.
- Create a Workbook instance and get a worksheet
- Write Data to specified cells:
- Iterate through the rows and columns in the list.
- Assign the data in the list to the corresponding Excel cells through the Worksheet.Range[].Value property.
- Save the Excel File.
Code Example:
- C#
using Spire.Xls;
using System.IO;
using System.Collections.Generic;
class TxtToExcelConverter
{
static void Main()
{
// Open a text file and read all lines in it
string[] lines = File.ReadAllLines("Data.txt");
// Create a list to store the data in text file
List data = new List();
// Split data into rows and columns and add to the list
foreach (string line in lines)
{
data.Add(line.Trim().Split('\t')); // Adjust delimiter as needed
}
// Create a Workbook object
Workbook workbook = new Workbook();
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Iterate through the rows and columns in the data list
for (int row = 0; row < data.Count; row++)
{
for (int col = 0; col < data[row].Length; col++)
{
// Write the text data in specified cells
sheet.Range[row + 1, col + 1].Value = data[row][col];
// Set the header row to Bold
sheet.Range[1, col + 1].Style.Font.IsBold = true;
}
}
// Autofit columns
sheet.AllocatedRange.AutoFitColumns();
// Save the Excel file
workbook.SaveToFile("TXTtoExcel.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
Result:

Pro Tips for TXT to Excel Conversion
- Handling Different Delimiters:
If your TXT file uses a different delimiter (e.g., space, comma, semicolon), modify the parameter of the Split(params char[] separator) method.
- Format Cells:
After a text file being converted to an Excel file, you can take advantage of the Spire.XLS library’s rich features to format cells, such as setting the background colors, adding cell borders, applying number formats, etc.
Conclusion
By following this step-by-step guide, you can efficiently transform unstructured text data into organized Excel spreadsheets, which is ideal for data analysis, reporting, and management. Remember to optimize your implementation for your specific delimiters and leverage Spire.XLS's advanced features for complex conversion scenarios.
Get a Free License
To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.