Knowledgebase (2311)
Children categories
Extracting text from PDF documents directly within a React application using JavaScript provides a streamlined, self-contained solution for handling dynamic content. Given that PDFs remain a ubiquitous format for reports, forms, and data sharing, parsing their contents on the client side enables developers to build efficient applications without relying on external services. By integrating Spire.PDF for JavaScript into React, development teams gain full control over data processing, reduce latency by eliminating server-side dependencies, and deliver real-time user experiences—all while ensuring that sensitive information remains secure within the browser.
In this article, we explore how to use Spire.PDF for JavaScript to extract text from PDF documents in React applications, simplifying the integration of robust PDF content extraction features.
- General Steps for Extracting PDF Text Using JavaScript
- Extract PDF Text with Layout Preservation
- Extract PDF Text without Layout Preservation
- Extract PDF Text from Specific Page Areas
- Extract Highlighted Text from PDF
Install Spire.PDF for JavaScript
To get started with extracting text from PDF documents with JavaScript in a React application, you can either download Spire.PDF for JavaScript from our website or install it via npm with the following command:
npm i spire.pdf
After that, copy the "Spire.Pdf.Base.js" and "Spire.Pdf.Base.wasm" files to the public folder of your project.
For more details, refer to the documentation: How to Integrate Spire.PDF for JavaScript in a React Project
General Steps for Extracting PDF Text Using JavaScript
Spire.PDF for JavaScript provides a WebAssembly module that enables PDF document processing using simple JavaScript code in React applications. Developers can utilize the PdfTextExtractor class to handle text extraction tasks efficiently. The general steps for extracting text from PDF documents using Spire.PDF for JavaScript in React are as follows:
- Load the Spire.Pdf.Base.js file to initialize the WebAssembly module.
- Fetch the PDF files into the Virtual File System (VFS) using the wasmModule.FetchFileToVFS() method.
- Create an instance of the PdfDocument class using the wasmModule.PdfDocument.Create() method.
- Load the PDF document from the VFS into the PdfDocument instance using the PdfDocument.LoadFromFile() method.
- Create an instance of the PdfTextExtractOptions class using the wasmModule.PdfTextExtractOptions.Create() method and configure the text extraction options.
- Retrieve a PDF page using the PdfDocument.Pages.get_Item() method or iterate through the document's pages.
- Create an instance of the PdfTextExtractor class with the page object using the wasmModule.PdfTextExtractor.Create() method.
- Extract text from the page using the PdfTextExtractor.ExtractText() method.
- Download the extracted text or process it as needed.
The PdfTextExtractOptions class allows customization of extraction settings, supporting features such as simple extraction, extracting specific page areas, and retrieving hidden text. The following table outlines the properties of the PdfTextExtractOptions class and their functions:
| Property | Description |
| IsSimpleExtraction | Specifies whether to perform simple text extraction. |
| IsExtractAllText | Specifies whether to extract all text. |
| ExtractArea | Defines the extraction area. |
| IsShowHiddenText | Specifies whether to extract hidden text. |
Extract PDF Text with Layout Preservation
Using the PdfTextExtractor.ExtractText() method with default options enables text extraction while preserving the original text layout of the PDF pages. Below is a code example and the corresponding extraction result:
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to store the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spirepdf from the global window object
const { Module, spirepdf } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepdf);
};
} catch (err) {
// Log any errors that occur during module loading
console.error('Failed to load the WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Pdf.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to extract all text from a PDF document
const ExtractPDFText = async () => {
if (wasmModule) {
// Specify the input and output file names
const inputFileName = 'Sample.pdf';
const outputFileName = 'PDFTextWithLayout.txt';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create an instance of the PdfDocument class
const pdf = wasmModule.PdfDocument.Create();
// Load the PDF document from the VFS
pdf.LoadFromFile(inputFileName);
// Create a string object to store the extracted text
let text = '';
// Create an instance of the PdfTextExtractOptions class
const extractOptions = wasmModule.PdfTextExtractOptions.Create();
// Iterate through each page of the PDF document
for (let i = 0; i < pdf.Pages.Count; i++) {
// Get the current page
const page = pdf.Pages.get_Item(i);
// Create an instance of the PdfTextExtractor class
const textExtractor = wasmModule.PdfTextExtractor.Create(page);
// Extract the text from the current page and add it to the text string
text += textExtractor.ExtractText(extractOptions);
}
// Create a Blob object from the text string and download it
const blob = new Blob([text], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${outputFileName}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Extract Text from PDF Using JavaScript in React</h1>
<button onClick={ExtractPDFText} disabled={!wasmModule}>
Extract and Download
</button>
</div>
);
}
export default App;

Extract PDF Text without Layout Preservation
Setting the PdfTextExtractOptions.IsSimpleExtraction property to true enables a simple text extraction strategy, allowing text extraction from PDF pages without preserving the layout. In this approach, blank spaces are not retained. Instead, the program tracks the Y position of each text string and inserts line breaks whenever the Y position changes.
Below is a code example demonstrating text extraction without layout preservation using Spire.PDF for JavaScript, along with the extraction result:
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to store the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spirepdf from the global window object
const { Module, spirepdf } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepdf);
};
} catch (err) {
// Log any errors that occur during module loading
console.error('Failed to load the WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Pdf.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to extract all text from a PDF document without layout preservation
const ExtractPDFText = async () => {
if (wasmModule) {
// Specify the input and output file names
const inputFileName = 'Sample.pdf';
const outputFileName = 'PDFTextWithoutLayout.txt';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create an instance of the PdfDocument class
const pdf = wasmModule.PdfDocument.Create();
// Load the PDF document from the VFS
pdf.LoadFromFile(inputFileName);
// Create a string object to store the extracted text
let text = '';
// Create an instance of the PdfTextExtractOptions class
const extractOptions = wasmModule.PdfTextExtractOptions.Create();
// Enable simple text extraction to extract text without preserving layout
extractOptions.IsSimpleExtraction = true;
// Iterate through each page of the PDF document
for (let i = 0; i < pdf.Pages.Count; i++) {
// Get the current page
const page = pdf.Pages.get_Item(i);
// Create an instance of the PdfTextExtractor class
const textExtractor = wasmModule.PdfTextExtractor.Create(page);
// Extract the text from the current page and add it to the text string
text += textExtractor.ExtractText(extractOptions);
}
// Create a Blob object from the text string and download it
const blob = new Blob([text], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${outputFileName}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Extract Text from PDF Without Layout Preservation Using JavaScript in React</h1>
<button onClick={ExtractPDFText} disabled={!wasmModule}>
Extract and Download
</button>
</div>
);
}
export default App;

Extract PDF Text from Specific Page Areas
The PdfTextExtractOptions.ExtractArea property allows users to define a specific area using a RectangleF object to extract only the text within that area from a PDF page. This method helps exclude unwanted fixed content from the extraction process. The following code example and extraction result illustrate this functionality:
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to store the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spirepdf from the global window object
const { Module, spirepdf } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepdf);
};
} catch (err) {
// Log any errors that occur during module loading
console.error('Failed to load the WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Pdf.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to extract text from a specific area of a PDF page
const ExtractPDFText = async () => {
if (wasmModule) {
// Specify the input and output file names
const inputFileName = 'Sample.pdf';
const outputFileName = 'PDFTextPageArea.txt';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create an instance of the PdfDocument class
const pdf = wasmModule.PdfDocument.Create();
// Load the PDF document from the VFS
pdf.LoadFromFile(inputFileName);
// Create a string object to store the extracted text
let text = '';
// Get a page from the PDF document
const page = pdf.Pages.get_Item(0);
// Create an instance of the PdfTextExtractOptions class
const extractOptions = wasmModule.PdfTextExtractOptions.Create();
// Set the page area to extract text from using a RectangleF object
extractOptions.ExtractArea = wasmModule.RectangleF.Create({ x: 0, y: 500, width: page.Size.Width, height: 200});
// Create an instance of the PdfTextExtractor class
const textExtractor = wasmModule.PdfTextExtractor.Create(page);
// Extract the text from specified area of the page
text = textExtractor.ExtractText(extractOptions);
// Create a Blob object from the text string and download it
const blob = new Blob([text], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${outputFileName}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Extract Text from a PDF Page Area Using JavaScript in React</h1>
<button onClick={ExtractPDFText} disabled={!wasmModule}>
Extract and Download
</button>
</div>
);
}
export default App;

Extract Highlighted Text from PDF
Text highlighting in PDF documents is achieved using annotation features. With Spire.PDF for JavaScript, we can retrieve all annotations on a PDF page via the PdfPageBase.Annotations property. By checking whether each annotation is an instance of the PdfTextMarkupAnnotationWidget class, we can identify highlight annotations. Once identified, we can use the PdfTextExtractOptions.Bounds property to obtain the bounding rectangles of these annotations and set them as extraction areas, thereby extracting only the highlighted text.
The following code example demonstrates this process along with the extracted result:
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to store the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spirepdf from the global window object
const { Module, spirepdf } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepdf);
};
} catch (err) {
// Log any errors that occur during module loading
console.error('Failed to load the WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Pdf.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to extract highlighted text from PDF
const ExtractPDFText = async () => {
if (wasmModule) {
// Specify the input and output file names
const inputFileName = 'Sample.pdf';
const outputFileName = 'PDFTextHighlighted.txt';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create an instance of the PdfDocument class
const pdf = wasmModule.PdfDocument.Create();
// Load the PDF document from the VFS
pdf.LoadFromFile(inputFileName);
// Create a string object to store the extracted text
let text = '';
// Iterate through each page of the PDF document
for (const page of pdf.Pages) {
// Iterate through each annotation on the page
for (let i = 0; i < page.Annotations.Count; i++) {
// Get the current annotation
const annotation = page.Annotations.get_Item(i)
// Check if the annotation is an instance of PdfTextMarkupAnnotation
if (annotation instanceof wasmModule.PdfTextMarkupAnnotationWidget) {
// Get the bounds of the annotation
const bounds = annotation.Bounds;
// Create an instance of PdfTextExtractOptions
const extractOptions = wasmModule.PdfTextExtractOptions.Create();
// Set the bounds of the highlight annotation as the extraction area
extractOptions.ExtractArea = bounds;
//
const textExtractor = wasmModule.PdfTextExtractor.Create(page)
// Extract the highlighted text and append it to the text string
text += textExtractor.ExtractText(extractOptions);
}
}
}
// Create a Blob object from the text string and download it
const blob = new Blob([text], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${outputFileName}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Extract Highlighted Text from PDF Using JavaScript in React</h1>
<button onClick={ExtractPDFText} disabled={!wasmModule}>
Extract and Download
</button>
</div>
);
}
export default App;

Get a Free License
To fully experience the capabilities of Spire.PDF for JavaScript without any evaluation limitations, you can request a free 30-day trial license.
Incorporating a watermark to Word documents is a simple yet impactful way to protect your content and assert ownership. Whether you're marking a draft as confidential or branding a business document, watermarks can convey essential information without distracting from your text.
In this article, you will learn how to add and customize watermarks in Word documents in a React application using Spire.Doc for JavaScript.
Install Spire.Doc for JavaScript
To get started with adding watermarks to Word in a React application, you can either download Spire.Doc for JavaScript from our website or install it via npm with the following command:
npm i spire.doc
After that, copy the "Spire.Doc.Base.js" and "Spire.Doc.Base.wasm" files to the public folder of your project. Additionally, include the required font files to ensure accurate text rendering.
For more details, refer to the documentation: How to Integrate Spire.Doc for JavaScript in a React Project
Add a Text Watermark to Word in React
Spire.Doc for JavaScript provides the TextWatermark class, enabling users to create customizable text watermarks with their preferred text and font effects. Once the TextWatermark object is created, it can be applied to the entire document using the Document.Watermark property.
The steps to add a text watermark to Word in React are as follows:
- Load the necessary font file and input Word document into the virtual file system (VFS).
- Create a Document object using the wasmModule.Document.Create() method.
- Load the Word file using the Document.LoadFromFile() method.
- Create a TextWatermark object using the wasmModule.TextWatermark.Create() method.
- Customize the watermark's text, font size, font name, and color using the properties under the TextWatermark object.
- Apply the text watermark to the document using the Document.Watermark property.
- Save the document and trigger a download.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Doc from the global window object
const { Module, spiredoc } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function add a text watermark
const AddWatermark = async () => {
if (wasmModule) {
// Load the required font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS("ARIALUNI.TTF","/Library/Fonts/",`${process.env.PUBLIC_URL}/`);
// Load the input Word file into the VFS
const inputFileName = 'input.docx';
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create a Document object
const doc = wasmModule.Document.Create();
// Load the Word document
doc.LoadFromFile(inputFileName);
// Create a TextWatermark instance
let txtWatermark = wasmModule.TextWatermark.Create();
// Set the text for the watermark
txtWatermark.Text = "Do Not Copy";
// Set the font size and name for the text
txtWatermark.FontSize = 58;
txtWatermark.FontName = "Arial"
// Set the color of the text
txtWatermark.Color = wasmModule.Color.get_Blue();
// Set the layout of the watermark to diagonal
txtWatermark.Layout = wasmModule.WatermarkLayout.Diagonal;
// Apply the text watermark to the document
doc.Watermark = txtWatermark;
// Define the output file name
const outputFileName = "TextWatermark.docx";
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2013});
// Read the generated file from VFS
const fileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the file
const blob = new Blob([fileArray], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
doc.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Add a Text Watermark to Word in React</h1>
<button onClick={AddWatermark} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;
Run the code to launch the React app at localhost:3000. Click "Convert", and a "Save As" window will appear, prompting you to save the output file in your chosen folder.

Here is a screenshot of the generated Word file that includes a text watermark:

Add an Image Watermark to Word in React
Spire.Doc for JavaScript provides the PictrueWatermark to help configure the image resource, scaling, washout effect for image watermarks in Word. Once a PictureWatermak object is created, you can apply it to an entire document using the Document.Watermark property.
Steps to add an image watermark to a Word document in React:
- Load the image file and input Word document into the virtual file system (VFS).
- Create a Document object using the wasmModule.Document.Create() method.
- Load the Word file using the Document.LoadFromFile() method.
- Create a PictureWatermark object using the wasmModule.PictureWatermark.Create() method.
- Set the image resource, scaling, and washout effect for the watermark using the methods and properties under the PictureWatermark object.
- Apply the image watermark to the document using the Document.Watermark property.
- Save the document and trigger a download.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Doc from the global window object
const { Module, spiredoc } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function add an image watermark
const AddWatermark = async () => {
if (wasmModule) {
// Load an image file into the virtual file system (VFS)
const imageFileName = 'company_logo.png';
await wasmModule.FetchFileToVFS(imageFileName, '', `${process.env.PUBLIC_URL}/`);
// Load the input Word file into the VFS
const inputFileName = 'input.docx';
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create a Document object
const doc = wasmModule.Document.Create();
// Load the Word document
doc.LoadFromFile(inputFileName);
// Create a new PictureWatermark instance
const pictureWatermark = wasmModule.PictureWatermark.Create();
// Set the picture
pictureWatermark.SetPicture(imageFileName);
// Set the scaling factor of the image
pictureWatermark.Scaling = 150;
// Disable washout effect
pictureWatermark.IsWashout = false;
// Apply the image watermark to the document
doc.Watermark = pictureWatermark;
// Define the output file name
const outputFileName = 'ImageWatermark.docx';
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2013});
// Read the generated file from VFS
const fileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the file
const blob = new Blob([fileArray], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
doc.Dispose();
}
};
return (
Add an Image Watermark to Word in React
);
}
export default App;

Get a Free License
To fully experience the capabilities of Spire.Doc for JavaScript without any evaluation limitations, you can request a free 30-day trial license.
Slicers in Excel offer a user-friendly way to filter data in pivot tables and tables, making data analysis both visually appealing and interactive. Unlike traditional filter options, which can be less intuitive, slicers present filter choices as buttons. This allows users to quickly and easily refine their data views. Whether you are handling large datasets or building dynamic dashboards, slicers improve the user experience by providing immediate feedback on the selected criteria. This article explains how to add, update, and remove slicers in Excel in C# using Spire.XLS for .NET.
- Add Slicers to Tables in Excel
- Add Slicers to Pivot Tables in Excel
- Update Slicers in Excel
- Remove Slicers from Excel
Install Spire.XLS for .NET
To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.XLS
Add Slicers to Tables in Excel
Spire.XLS for .NET offers the Worksheet.Slicers.Add(IListObject table, string destCellName, int index) method to add a slicer to a table in an Excel worksheet. The detailed steps are as follows.
- Create an object of the Workbook class.
- Get the first worksheet using the Workbook.Worksheets[0] property.
- Add data to the worksheet using the Worksheet.Range[].Value property.
- Add a table to the worksheet using the Worksheet.IListObjects.Create() method.
- Add a slicer to the table using the Worksheeet.Slicers.Add(IListObject table, string destCellName, int index) method.
- Save the resulting file using the Workbook.SaveToFile() method.
- C#
using Spire.Xls;
using Spire.Xls.Core;
namespace AddSlicerToTable
{
internal class Program
{
static void Main(string[] args)
{
// Create an object of the Workbook class
Workbook workbook = new Workbook();
// Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Add data to the worksheet
worksheet.Range["A1"].Value = "Fruit";
worksheet.Range["A2"].Value = "Grape";
worksheet.Range["A3"].Value = "Blueberry";
worksheet.Range["A4"].Value = "Kiwi";
worksheet.Range["A5"].Value = "Cherry";
worksheet.Range["A6"].Value = "Grape";
worksheet.Range["A7"].Value = "Blueberry";
worksheet.Range["A8"].Value = "Kiwi";
worksheet.Range["A9"].Value = "Cherry";
worksheet.Range["B1"].Value = "Year";
worksheet.Range["B2"].Value2 = 2020;
worksheet.Range["B3"].Value2 = 2020;
worksheet.Range["B4"].Value2 = 2020;
worksheet.Range["B5"].Value2 = 2020;
worksheet.Range["B6"].Value2 = 2021;
worksheet.Range["B7"].Value2 = 2021;
worksheet.Range["B8"].Value2 = 2021;
worksheet.Range["B9"].Value2 = 2021;
worksheet.Range["C1"].Value = "Sales";
worksheet.Range["C2"].Value2 = 50;
worksheet.Range["C3"].Value2 = 60;
worksheet.Range["C4"].Value2 = 70;
worksheet.Range["C5"].Value2 = 80;
worksheet.Range["C6"].Value2 = 90;
worksheet.Range["C7"].Value2 = 100;
worksheet.Range["C8"].Value2 = 110;
worksheet.Range["C9"].Value2 = 120;
//Create a table from the specific data range
IListObject table = worksheet.ListObjects.Create("Fruit Sales", worksheet.Range["A1:C9"]);
// Add a slicer to cell "A11" to filter the data based on the first column of the table
int index = worksheet.Slicers.Add(table, "A11", 0);
// Set name and style for the slicer
worksheet.Slicers[index].Name = "Fruit";
worksheet.Slicers[index].StyleType = SlicerStyleType.SlicerStyleLight1;
//Save the resulting file
workbook.SaveToFile("AddSlicerToTable.xlsx", ExcelVersion.Version2013);
workbook.Dispose();
}
}
}

Add Slicers to Pivot Tables in Excel
In addition to adding slicers to tables, Spire.XLS for .NET also enables you to add slicers to pivot tables in Excel using the Worksheet.Slicers.Add(IPivotTable pivot, string destCellName, int baseFieldIndex) method. The detailed steps are as follows.
- Create an object of the Workbook class.
- Get the first worksheet using the Workbook.Worksheets[0] property.
- Add data to the worksheet using the Worksheet.Range[].Value property.
- Create a pivot cache from the data using the Workbook.PivotCaches.Add() method.
- Create a pivot table from the pivot cache using the Worksheet.PivotTables.Add() method.
- Drag the pivot fields to the row, column, and data areas. Then calculate the data in the pivot table.
- Add a slicer to the pivot table using the Worksheet.Slicers.Add(IPivotTable pivot, string destCellName, int baseFieldIndex) method.
- Set the properties, such as the name, width, height, style, and cross filter type for the slicer.
- Calculate the data in the pivot table.
- Save the resulting file using the Workbook.SaveToFile() method.
- C#
using Spire.Xls;
using Spire.Xls.Core;
namespace AddSlicerToPivotTable
{
internal class Program
{
static void Main(string[] args)
{
// Create an object of the Workbook class
Workbook workbook = new Workbook();
// Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Add data to the worksheet
worksheet.Range["A1"].Value = "Fruit";
worksheet.Range["A2"].Value = "Grape";
worksheet.Range["A3"].Value = "Blueberry";
worksheet.Range["A4"].Value = "Kiwi";
worksheet.Range["A5"].Value = "Cherry";
worksheet.Range["A6"].Value = "Grape";
worksheet.Range["A7"].Value = "Blueberry";
worksheet.Range["A8"].Value = "Kiwi";
worksheet.Range["A9"].Value = "Cherry";
worksheet.Range["B1"].Value = "Year";
worksheet.Range["B2"].Value2 = 2020;
worksheet.Range["B3"].Value2 = 2020;
worksheet.Range["B4"].Value2 = 2020;
worksheet.Range["B5"].Value2 = 2020;
worksheet.Range["B6"].Value2 = 2021;
worksheet.Range["B7"].Value2 = 2021;
worksheet.Range["B8"].Value2 = 2021;
worksheet.Range["B9"].Value2 = 2021;
worksheet.Range["C1"].Value = "Sales";
worksheet.Range["C2"].Value2 = 50;
worksheet.Range["C3"].Value2 = 60;
worksheet.Range["C4"].Value2 = 70;
worksheet.Range["C5"].Value2 = 80;
worksheet.Range["C6"].Value2 = 90;
worksheet.Range["C7"].Value2 = 100;
worksheet.Range["C8"].Value2 = 110;
worksheet.Range["C9"].Value2 = 120;
// Create a pivot cache from the specific data range
CellRange dataRange = worksheet.Range["A1:C9"];
PivotCache cache = workbook.PivotCaches.Add(dataRange);
// Create a pivot table from the pivot cache
PivotTable pt = worksheet.PivotTables.Add("Fruit Sales", worksheet.Range["A12"], cache);
// Drag the fields to the row and column areas
PivotField pf = pt.PivotFields["Fruit"] as PivotField;
pf.Axis = AxisTypes.Row;
PivotField pf2 = pt.PivotFields["Year"] as PivotField;
pf2.Axis = AxisTypes.Column;
// Drag the field to the data area
pt.DataFields.Add(pt.PivotFields["Sales"], "Sum of Sales", SubtotalTypes.Sum);
// Set style for the pivot table
pt.BuiltInStyle = PivotBuiltInStyles.PivotStyleMedium10;
// Calculate the pivot table data
pt.CalculateData();
// Add a Slicer to the pivot table
int index_1 = worksheet.Slicers.Add(pt, "F12", 0);
// Set the name, width, height, and style for the slicer
worksheet.Slicers[index_1].Name = "Fruit";
worksheet.Slicers[index_1].Width = 100;
worksheet.Slicers[index_1].Height = 120;
worksheet.Slicers[index_1].StyleType = SlicerStyleType.SlicerStyleLight2;
// Set the cross filter type for the slicer
XlsSlicerCache slicerCache = worksheet.Slicers[index_1].SlicerCache;
slicerCache.CrossFilterType = SlicerCacheCrossFilterType.ShowItemsWithNoData;
// Calculate the pivot table data
pt.CalculateData();
// Save the resulting file
workbook.SaveToFile("AddSlicerToPivotTable.xlsx", ExcelVersion.Version2013);
workbook.Dispose();
}
}
}

Update Slicers in Excel
You can update the properties of a slicer, such as its style, name, caption, and more using the corresponding properties of the XlsSlicer class. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using the Workbook.LoadFromFile() method.
- Get a specific worksheet by its index using the Workbook.Worksheets[index] property.
- Get a specific slicer from the worksheet by its index using the Worksheet.Slicers[index] property.
- Update the properties of the slicer, such as its style, name, caption, and cross filter type using the properties of the XlsSlicer class.
- Save the resulting file using the Workbook.SaveToFile() method.
- C#
using Spire.Xls;
using Spire.Xls.Core;
namespace UpdateSlicer
{
internal class Program
{
static void Main(string[] args)
{
// Create an object of the Workbook class
Workbook workbook = new Workbook();
// Load an Excel file
workbook.LoadFromFile("AddSlicerToTable.xlsx");
// Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Get the first slicer in the worksheet
XlsSlicer slicer = worksheet.Slicers[0];
// Change the style, name, and caption for the slicer
slicer.StyleType = SlicerStyleType.SlicerStyleDark4;
slicer.Name = "Slicer";
slicer.Caption = "Slicer";
// Change the cross filter type for the slicer
slicer.SlicerCache.CrossFilterType = SlicerCacheCrossFilterType.ShowItemsWithDataAtTop;
// Deselect an item in the slicer
XlsSlicerCacheItemCollection slicerCacheItems = slicer.SlicerCache.SlicerCacheItems;
XlsSlicerCacheItem xlsSlicerCacheItem = slicerCacheItems[0];
xlsSlicerCacheItem.Selected = false;
// Save the resulting file
workbook.SaveToFile("UpdateSlicer.xlsx", ExcelVersion.Version2013);
workbook.Dispose();
}
}
}

Remove Slicers from Excel
You can remove a specific slicer from an Excel worksheet using the Worksheet.Slicers.RemoveAt() method, or remove all slicers at once using the Worksheet.Slicers.Clear() method. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using the Workbook.LoadFromFile() method.
- Get a specific worksheet by its index using the Workbook.Worksheets[index] property.
- Remove a specific slicer from the worksheet by its index using the Worksheet.Slicers.RemoveAt(index) method. Or remove all slicers from the worksheet using the Worksheet.Slicers.Clear() method.
- Save the resulting file using the Workbook.SaveToFile() method.
- C#
using Spire.Xls;
using Spire.Xls.Core;
namespace RemoveSlicer
{
internal class Program
{
static void Main(string[] args)
{
// Create an object of the Workbook class
Workbook workbook = new Workbook();
// Load an Excel file
workbook.LoadFromFile("AddSlicerToTable.xlsx");
// Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Remove the first slicer by index
worksheet.Slicers.RemoveAt(0);
//// Or remove all slicers
//worksheet.Slicers.Clear();
// Save the resulting file
workbook.SaveToFile("RemoveSlicer.xlsx", ExcelVersion.Version2013);
workbook.Dispose();
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.