read pdf in java

In today's data-driven landscape, reading PDF files effectively is essential for Java developers. Whether you're handling scanned invoices, structured reports, or image-rich documents, the ability to read PDFs in Java can enhance workflows and reveal critical insights.

This guide will walk you through practical implementations using Spire.PDF for Java to master PDF reading in Java. You will learn to extract searchable text, retrieve embedded images, read tabular data, and perform OCR on scanned PDF documents.

Table of Contents:

Java Library for Reading PDF Content

When it comes to reading PDF in Java, choosing the right library is half the battle. Spire.PDF stands out as a robust, feature-rich solution for developers. It supports text extraction, image retrieval, table parsing, and even OCR integration. Its intuitive API and comprehensive documentation make it ideal for both beginners and experts.

To start extracting PDF content, download Spire.PDF for Java from our website and add it as a dependency in your project. If you’re using Maven, include the following in your pom.xml:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>11.5.2</version>
    </dependency>
</dependencies>

Below, we’ll explore how to leverage Spire.PDF for various PDF reading tasks.

Extract Text from Searchable PDFs in Java

Searchable PDFs store text in a machine-readable format, allowing for efficient content extraction. The PdfTextExtractor class in Spire.PDF provides a straightforward way to access page content, while PdfTextExtractOptions allows for flexible extraction settings, including options for handling special text layouts and specifying areas for extraction.

Step-by-Step Guide

  1. Initialize a new instance of PdfDocument to work with your PDF file.
  2. Use the loadFromFile method to load the desired PDF document.
  3. Loop through each page of the PDF using a for loop.
  4. For each page, create an instance of PdfTextExtractor to facilitate text extraction.
  5. Create a PdfTextExtractOptions object to specify how text should be extracted, including any special strategies.
  6. Call the extract method on the PdfTextExtractor instance to retrieve the text from the page.
  7. Write the extracted text to a text file.

The example below shows how to retrieve text from every page of a PDF and output it to individual text files.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextExtractOptions;
import com.spire.pdf.texts.PdfTextExtractor;
import com.spire.pdf.texts.PdfTextStrategy;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ExtractTextFromSearchablePdf {

    public static void main(String[] args) throws IOException {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

        // Iterate through all pages
        for (int i = 0; i < doc.getPages().getCount(); i++) {
            // Get the current page
            PdfPageBase page = doc.getPages().get(i);

            // Create a PdfTextExtractor object
            PdfTextExtractor textExtractor = new PdfTextExtractor(page);

            // Create a PdfTextExtractOptions object
            PdfTextExtractOptions extractOptions = new PdfTextExtractOptions();

            // Specify extract option
            extractOptions.setStrategy(PdfTextStrategy.None);

            // Extract text from the page
            String text = textExtractor.extract(extractOptions);

            // Define the output file path
            Path outputPath = Paths.get("output/Extracted_Page_" + (i + 1) + ".txt");

            // Write to a txt file
            Files.write(outputPath, text.getBytes());
        }

        // Close the document
        doc.close();
    }
}

Result:

Input PDF document and output txt file with text extracted from the PDF.

Retrieve Images from PDFs in Java

The PdfImageHelper class in Spire.PDF enables efficient extraction of embedded images from PDF documents. It identifies images using PdfImageInfo objects, allowing for easy saving as standard image files.

Step-by-Step Guide

  1. Initialize a new instance of PdfDocument to work with your PDF file.
  2. Use the loadFromFile method to load the desired PDF.
  3. Instantiate PdfImageHelper to assist with image extraction.
  4. Loop through each page of the PDF.
  5. For each page, retrieve all image information using the getImagesInfo method.
  6. Loop through the retrieved image information, extract each image, and save it as a PNG file.

The following example extracts all embedded images from a PDF document and saves them as individual PNG files.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.utilities.PdfImageHelper;
import com.spire.pdf.utilities.PdfImageInfo;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ExtractAllImages {

    public static void main(String[] args) throws IOException {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

        // Create a PdfImageHelper object
        PdfImageHelper imageHelper = new PdfImageHelper();

        // Declare an int variable
        int m = 0;

        // Iterate through the pages
        for (int i = 0; i < doc.getPages().getCount(); i++) {

            // Get a specific page
            PdfPageBase page = doc.getPages().get(i);

            // Get all image information from the page
            PdfImageInfo[] imageInfos = imageHelper.getImagesInfo(page);

            // Iterate through the image information
            for (int j = 0; j < imageInfos.length; j++)
            {
                // Get a specific image information
                PdfImageInfo imageInfo = imageInfos[j];

                // Get the image
                BufferedImage image = imageInfo.getImage();
                File file = new File(String.format("output/Image-%d.png",m));
                m++;

                // Save the image file in PNG format
                ImageIO.write(image, "PNG", file);
            }
        }

        // Clear up resources
        doc.dispose();
    }
}

Result:

Input PDF document and image file extracted from the PDF.

Read Table Data from PDF Files in Java

For PDF tables that need conversion to structured data, PdfTableExtractor intelligently recognizes cell boundaries and relationships. The resulting PdfTable objects maintain the original table organization, allowing for cell-level data export.

Step-by-Step Guide

  1. Initialize an instance of PdfDocument to handle your PDF file.
  2. Use the loadFromFile method to open the desired PDF.
  3. Instantiate PdfTableExtractor to facilitate table extraction.
  4. Iterate through each page of the PDF to extract tables.
  5. For each page, retrieve tables into a PdfTable array using the extractTable method.
  6. For each table, iterate through its rows and columns to extract data.
  7. Write the extracted data to individual text files.

This Java code extracts table data from a PDF document and saves each table as a separate text file.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.utilities.PdfTable;
import com.spire.pdf.utilities.PdfTableExtractor;

import java.io.FileWriter;

public class ExtractTableData {
    public static void main(String[] args) throws Exception {

        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

        // Create a PdfTableExtractor instance
        PdfTableExtractor extractor = new PdfTableExtractor(doc);

        // Initialize a table counter
        int tableCounter = 1;

        // Loop through the pages in the PDF
        for (int pageIndex = 0; pageIndex < doc.getPages().getCount(); pageIndex++) {

            // Extract tables from the current page into a PdfTable array
            PdfTable[] tableLists = extractor.extractTable(pageIndex);

            // If any tables are found
            if (tableLists != null && tableLists.length > 0) {

                // Loop through the tables in the array
                for (PdfTable table : tableLists) {

                    // Create a StringBuilder for the current table
                    StringBuilder builder = new StringBuilder();

                    // Loop through the rows in the current table
                    for (int i = 0; i < table.getRowCount(); i++) {

                        // Loop through the columns in the current table
                        for (int j = 0; j < table.getColumnCount(); j++) {

                            // Extract data from the current table cell and append to the StringBuilder 
                            String text = table.getText(i, j);
                            builder.append(text).append(" | ");
                        }
                        builder.append("\r\n");
                    }

                    // Write data into a separate .txt document for each table
                    FileWriter fw = new FileWriter("output/Table_" + tableCounter + ".txt");
                    fw.write(builder.toString());
                    fw.flush();
                    fw.close();

                    // Increment the table counter
                    tableCounter++;
                }
            }
        }

        // Clear up resources
        doc.dispose();
    }
}

Result:

Input PDF document and txt file containing table data extracted from the PDF.

Convert Scanned PDFs to Text via OCR

Scanned PDFs require special handling through OCR engine such as Spire.OCR for Java. The solution first converts pages to images using Spire.PDF's rendering engine, then applies Spire.OCR's recognition capabilities via the OcrScanner class. This two-step approach effectively transforms physical document scans into editable text while supporting multiple languages.

Step 1. Install Spire.OCR and Configure the Environment

OcrScanner scanner = new OcrScanner();
configureOptions.setModelPath("D:\\win-x64");// model path

For detailed steps, refer to: Extract Text from Images Using the New Model of Spire.OCR for Java

Step 2. Convert a Scanned PDF to Text

This code example converts each page of a scanned PDF into an image, applies OCR to extract text, and saves the results in a text file.

import com.spire.ocr.OcrException;
import com.spire.ocr.OcrScanner;
import com.spire.ocr.ConfigureOptions;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.PdfImageType;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ExtractTextFromScannedPdf {

    public static void main(String[] args) throws IOException, OcrException {

        // Create an instance of the OcrScanner class
        OcrScanner scanner = new OcrScanner();

        // Configure the scanner
        ConfigureOptions configureOptions = new ConfigureOptions();
        configureOptions.setModelPath("D:\\win-x64"); // Set model path
        configureOptions.setLanguage("English"); // Set language

        // Apply the configuration options
        scanner.ConfigureDependencies(configureOptions);

        // Load a PDF document
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

        // Prepare temporary directory
        String tempDirPath = "temp";
        new File(tempDirPath).mkdirs(); // Create temp directory

        StringBuilder allText = new StringBuilder();

        // Iterate through all pages
        for (int i = 0; i < doc.getPages().getCount(); i++) {

            // Convert page to image
            BufferedImage bufferedImage = doc.saveAsImage(i, PdfImageType.Bitmap);
            String imagePath = tempDirPath + File.separator + String.format("page_%d.png", i);
            ImageIO.write(bufferedImage, "PNG", new File(imagePath));

            // Perform OCR
            scanner.scan(imagePath);
            String pageText = scanner.getText().toString();
            allText.append(String.format("\n--- PAGE %d ---\n%s\n", i + 1, pageText));

            // Clean up temp image
            new File(imagePath).delete();
        }

        // Save all extracted text to a file
        Path outputTxtPath = Paths.get("output", "extracted_text.txt");
        Files.write(outputTxtPath, allText.toString().getBytes());

        // Close the document
        doc.close();
        System.out.println("Text extracted to " + outputTxtPath);
    }
}

Conclusion

Mastering how to read PDF in Java opens up a world of possibilities for data extraction and document automation. Whether you’re dealing with searchable text, images, tables, or scanned documents, the right tools and techniques can simplify the process.

By leveraging libraries like Spire.PDF and integrating OCR for scanned files, you can build robust solutions tailored to your needs. Start experimenting with the code snippets provided and unlock the full potential of PDF processing in Java!

FAQs

Q1: Can I extract text from scanned PDFs using Java?

Yes, by combining Spire.PDF with Spire.OCR. Convert PDF pages to images and perform OCR to extract text.

Q2: What’s the best library for reading PDFs in Java?

Spire.PDF is highly recommended for its versatility and ease of use. It supports extraction of text, images, tables, and OCR integration.

Q3: Does Spire.PDF support extraction of PDF elements like metadata, attachments, and hyperlinks?

Yes, Spire.PDF provides comprehensive support for extracting:

  • Metadata (title, author, keywords)
  • Attachments (embedded files)
  • Hyperlinks (URLs and document links)

The library offers dedicated classes like PdfDocumentInformation for metadata and methods to retrieve embedded files ( PdfAttachmentCollection ) and hyperlinks ( PdfUriAnnotation ).

Q4: How to parse tables from PDFs into CSV/Excel programmatically?

Using Spire.PDF for Java, you can extract table data from PDFs, then seamlessly export it to Excel (XLSX) or CSV format with Spire.XLS for Java. For a step-by-step guide, refer to our tutorial: Export Table Data from PDF to Excel in Java.

Get a Free License

To fully experience the capabilities of Spire.PDF for Java without any evaluation limitations, you can request a free 30-day trial license.

In modern software development, generating dynamic Word documents from templates is a common requirement for applications that produce reports, contracts, invoices, or other business documents. Java developers seeking efficient solutions for document automation can leverage Spire.Doc for Java, a robust library for processing Word files without requiring Microsoft Office.

This guide explores how to use Spire.Doc for Java to create Word documents from templates. We will cover two key approaches: replacing text placeholders and modifying bookmark content.

Java Library for Generating Word Documents

Spire.Doc for Java is a powerful library that enables developers to create, manipulate, and convert Word documents. It provides an intuitive API that allows for various operations, including the modification of text, images, and bookmarks in existing documents.

To get started, download the library from our official website and import it into your Java project. If you're using Maven, include the following dependency in your pom.xml file:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>14.10.6</version>
    </dependency>
</dependencies>

Generate a Word Document by Replacing Text Placeholders

This method uses a template document containing marked placeholders (e.g., #name#, #date#) that are dynamically replaced with real data. Spire.Doc's Document.replace() method handles text substitutions efficiently, while additional APIs enable advanced replacements like inserting images at specified locations.

Steps to generate Word documents from templates by replacing text placeholders:

  • Initialize Document: A new Document object is created to work with the Word file.
  • Load the template: The template document with placeholders is loaded.
  • Create replacement mappings: A HashMap is created to store placeholder-replacement pairs.
  • Perform text replacement: The replace() method finds and replaces all instances of each placeholder.
  • Handle image insertion: The custom replaceTextWithImage() method replaces a text placeholder with an image.
  • Save the result: The modified document is saved to a specified path.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

import java.util.HashMap;
import java.util.Map;

public class ReplaceTextPlaceholders {

    public static void main(String[] args) {

        // Initialize a new Document object
        Document document = new Document();

        // Load the template Word file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\template.docx");

        // Map to hold text placeholders and their replacements
        Map<String, String> replaceDict = new HashMap<>();
        replaceDict.put("#name#", "John Doe");
        replaceDict.put("#gender#", "Male");
        replaceDict.put("#birthdate#", "January 15, 1990");
        replaceDict.put("#address#", "123 Main Street");
        replaceDict.put("#city#", "Springfield");
        replaceDict.put("#state#", "Illinois");
        replaceDict.put("#postal#", "62701");
        replaceDict.put("#country#", "United States");

        // Replace placeholders in the document with corresponding values
        for (Map.Entry<String, String> entry : replaceDict.entrySet()) {
            document.replace(entry.getKey(), entry.getValue(), true, true);
        }

        // Path to the image file
        String imagePath = "C:\\Users\\Administrator\\Desktop\\portrait.png";

        // Replace the placeholder “#photo#” with an image
        replaceTextWithImage(document, "#photo#", imagePath);

        // Save the modified document
        document.saveToFile("output/ReplacePlaceholders.docx", FileFormat.Docx);

        // Release resources
        document.dispose();
    }

    // Method to replace a placeholder in the document with an image
    static void replaceTextWithImage(Document document, String stringToReplace, String imagePath) {

        // Load the image from the specified path
        DocPicture pic = new DocPicture(document);
        pic.loadImage(imagePath);

        // Find the placeholder in the document
        TextSelection selection = document.findString(stringToReplace, false, true);

        // Get the range of the found text
        TextRange range = selection.getAsOneRange();
        int index = range.getOwnerParagraph().getChildObjects().indexOf(range);

        // Insert the image and remove the placeholder text
        range.getOwnerParagraph().getChildObjects().insert(index, pic);
        range.getOwnerParagraph().getChildObjects().remove(range);
    }
}

Output:

Screenshot of the input template file containing placeholders and the output Word document.

Generate a Word Document by Modifying Bookmark Content

This approach uses Word bookmarks to identify locations in the document where content should be inserted or modified. The BookmarksNavigator class in Spire.Doc streamlines the process by enabling direct access to bookmarks, allowing targeted content replacement while automatically preserving the document's original structure and formatting.

Steps to generate Word documents from templates by modifying bookmark content:

  • Initialize Document: A new Document object is initialized.
  • Load the template: The template document with predefined bookmarks is loaded.
  • Set up replacements: A HashMap is created to map bookmark names to their replacement values.
  • Navigate to bookmarks: A BookmarksNavigator is instantiated to navigate through bookmarks in the document.
  • Replace content: The replaceBookmarkContent() method updates the bookmark's content.
  • Save the result: The modified document is saved to a specified path.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import java.util.HashMap;
import java.util.Map;

public class ModifyBookmarkContent {

    public static void main(String[] args) {

        // Initialize a new Document object
        Document document = new Document();

        // Load the template Word file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\template.docx");

        // Define bookmark names and their replacement values
        Map<String, String> replaceDict = new HashMap<>();
        replaceDict.put("name", "Tech Innovations Inc.");
        replaceDict.put("year", "2015");
        replaceDict.put("headquarter", "San Francisco, California, USA");
        replaceDict.put("history", "Tech Innovations Inc. was founded by a group of engineers and " +
                "entrepreneurs with a vision to revolutionize the technology sector. Starting " +
                "with a focus on software development, the company expanded its portfolio to " +
                "include artificial intelligence and cloud computing solutions.");

        // Create a BookmarksNavigator to manage bookmarks in the document
        BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);

        // Iterate through the bookmarks
        for (Map.Entry<String, String> entry : replaceDict.entrySet()) {

            // Navigate to a specific bookmark
            bookmarkNavigator.moveToBookmark(entry.getKey());

            // Replace content
            bookmarkNavigator.replaceBookmarkContent(entry.getValue(), true);
        }

        // Save the modified document
        document.saveToFile("output/ReplaceBookmarkContent.docx", FileFormat.Docx);

        // Release resources
        document.dispose();
    }
}

Output:

Screenshot of the input template file containing bookmarks and the output Word document.

Conclusion

Both methods provide effective ways to generate documents from templates, but they suit different scenarios:

Text Replacement Method is best when:

  • You need simple text substitutions
  • You need to insert images at specific locations
  • You want to replace text anywhere in the document (not just specific locations)

Bookmark Method is preferable when:

  • You're working with complex documents where precise location matters
  • You need to replace larger sections of content or paragraphs
  • You want to preserve bookmarks for future updates

Spire.Doc also offers Mail Merge capabilities, enabling high-volume document generation from templates. This feature excels at producing personalized documents like mass letters or reports by merging template fields with external data sources like databases.

FAQs

Q1: Can I convert the generated Word document to PDF?

A: Yes, Spire.Doc for Java supports converting documents to PDF and other formats. Simply use saveToFile() with FileFormat.PDF.

Q2: How can I handle complex formatting in generated documents?

A: Prepare your template with all required formatting in Word, then use placeholders or bookmarks in locations where dynamic content should appear. The formatting around these markers will be preserved.

Q3: What's the difference between mail merge and text replacement?

A: Mail merge is specifically designed for merging database-like data with documents and supports features like repeating sections for records. Text replacement is simpler but doesn't handle tabular data as elegantly.

Get a Free License

To fully experience the capabilities of Spire.Doc for Java without any evaluation limitations, you can request a free 30-day trial license.

A Slicer in Excel is an interactive filtering tool that simplifies data analysis in pivot tables and tables. Unlike traditional dropdown menus, slicers present intuitive, clickable buttons, each representing a distinct value in the dataset (e.g., regions, product categories, or dates). With slicers, users can filter datasets to focus on specific subsets with just a single click, making analysis faster and more visually intuitive. In this guide, we will explore how to create new slicers, update existing slicers, and remove slicers in Excel using Java and the Spire.XLS for Java library.

Install Spire.XLS for Java

First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls</artifactId>
        <version>16.10.1</version>
    </dependency>
</dependencies>

Add Slicers to Tables in Excel

Spire.XLS for Java provides the Worksheet.getSlicers().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.getWorksheets.get(0) method.
  • Add data to the worksheet using the Worksheet.getRange().get().setValue() and Worksheet.getRange().get().setNumberValue() methods.
  • Add a table to the worksheet using the Worksheet.getIListObjects().create() method.
  • Add a slicer to the table using the Worksheeet.getSlicers().add(IListObject table, String destCellName, int index) method.
  • Save the resulting file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;
import com.spire.xls.core.IListObject;
import com.spire.xls.core.spreadsheet.slicer.*;

public class AddSlicerToTable {
    public static void main(String[] args) {
        // Create an object of the Workbook class
        Workbook workbook = new Workbook();

        // Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        // Add data to the worksheet
        worksheet.getRange().get("A1").setValue("Fruit");
        worksheet.getRange().get("A2").setValue("Grape");
        worksheet.getRange().get("A3").setValue("Blueberry");
        worksheet.getRange().get("A4").setValue("Kiwi");
        worksheet.getRange().get("A5").setValue("Cherry");
        worksheet.getRange().get("A6").setValue("Grape");
        worksheet.getRange().get("A7").setValue("Blueberry");
        worksheet.getRange().get("A8").setValue("Kiwi");
        worksheet.getRange().get("A9").setValue("Cherry");

        worksheet.getRange().get("B1").setValue("Year");
        worksheet.getRange().get("B2").setNumberValue(2020);
        worksheet.getRange().get("B3").setNumberValue(2020);
        worksheet.getRange().get("B4").setNumberValue(2020);
        worksheet.getRange().get("B5").setNumberValue(2020);
        worksheet.getRange().get("B6").setNumberValue(2021);
        worksheet.getRange().get("B7").setNumberValue(2021);
        worksheet.getRange().get("B8").setNumberValue(2021);
        worksheet.getRange().get("B9").setNumberValue(2021);

        worksheet.getRange().get("C1").setValue("Sales");
        worksheet.getRange().get("C2").setNumberValue(50);
        worksheet.getRange().get("C3").setNumberValue(60);
        worksheet.getRange().get("C4").setNumberValue(70);
        worksheet.getRange().get("C5").setNumberValue(80);
        worksheet.getRange().get("C6").setNumberValue(90);
        worksheet.getRange().get("C7").setNumberValue(100);
        worksheet.getRange().get("C8").setNumberValue(110);
        worksheet.getRange().get("C9").setNumberValue(120);

        // Create a table from the specific data range
        IListObject table = worksheet.getListObjects().create("Fruit Sales", worksheet.getRange().get("A1:C9"));

        // Add a slicer to cell "A11" to filter the data based on the first column of the table
        XlsSlicerCollection slicers = worksheet.getSlicers();
        int index = slicers.add(table, "A11", 0);

        // Set name and style for the slicer
        XlsSlicer slicer = slicers.get(index);
        slicer.setName("Fruit");
        slicer.setStyleType(SlicerStyleType.SlicerStyleLight1);

        // Save the resulting file
        workbook.saveToFile("AddSlicerToTable.xlsx", ExcelVersion.Version2013);
        workbook.dispose();
    }
}

Add Slicers to Tables in Excel

Add Slicers to Pivot Tables in Excel

Spire.XLS for Java also supports adding slicers to pivot tables using the Worksheet.getSlicers().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.getWorksheets.get(0) method.
  • Add data to the worksheet using the Worksheet.getRange().get().setValue() and Worksheet.getRange().get().setNumberValue() methods.
  • Create a pivot cache from the data using the Workbook.getPivotCaches().add() method.
  • Create a pivot table from the pivot cache using the Worksheet.getPivotTables().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.getSlicers().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.
  • Java
import com.spire.xls.*;
import com.spire.xls.core.IPivotField;
import com.spire.xls.core.IPivotTable;
import com.spire.xls.core.spreadsheet.slicer.*;

public class AddSlicerToPivotTable {
    public static void main(String[] args) {
        // Create an object of the Workbook class
        Workbook workbook = new Workbook();

        // Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        // Add data to the worksheet
        worksheet.getRange().get("A1").setValue("Fruit");
        worksheet.getRange().get("A2").setValue("Grape");
        worksheet.getRange().get("A3").setValue("Blueberry");
        worksheet.getRange().get("A4").setValue("Kiwi");
        worksheet.getRange().get("A5").setValue("Cherry");
        worksheet.getRange().get("A6").setValue("Grape");
        worksheet.getRange().get("A7").setValue("Blueberry");
        worksheet.getRange().get("A8").setValue("Kiwi");
        worksheet.getRange().get("A9").setValue("Cherry");

        worksheet.getRange().get("B1").setValue("Year");
        worksheet.getRange().get("B2").setNumberValue(2020);
        worksheet.getRange().get("B3").setNumberValue(2020);
        worksheet.getRange().get("B4").setNumberValue(2020);
        worksheet.getRange().get("B5").setNumberValue(2020);
        worksheet.getRange().get("B6").setNumberValue(2021);
        worksheet.getRange().get("B7").setNumberValue(2021);
        worksheet.getRange().get("B8").setNumberValue(2021);
        worksheet.getRange().get("B9").setNumberValue(2021);

        worksheet.getRange().get("C1").setValue("Sales");
        worksheet.getRange().get("C2").setNumberValue(50);
        worksheet.getRange().get("C3").setNumberValue(60);
        worksheet.getRange().get("C4").setNumberValue(70);
        worksheet.getRange().get("C5").setNumberValue(80);
        worksheet.getRange().get("C6").setNumberValue(90);
        worksheet.getRange().get("C7").setNumberValue(100);
        worksheet.getRange().get("C8").setNumberValue(110);
        worksheet.getRange().get("C9").setNumberValue(120);

        // Create a pivot cache from the specific data range
        CellRange dataRange = worksheet.getRange().get("A1:C9");
        PivotCache cache = workbook.getPivotCaches().add(dataRange);

        // Create a pivot table from the pivot cache
        PivotTable pt = worksheet.getPivotTables().add("Fruit Sales", worksheet.getRange().get("A12"), cache);

        // Drag the fields to the row and column areas
        IPivotField pf = pt.getPivotFields().get("Fruit");
        pf.setAxis(AxisTypes.Row);
        IPivotField pf2 = pt.getPivotFields().get("Year");
        pf2.setAxis(AxisTypes.Column);

        // Drag the field to the data area
        pt.getDataFields().add(pt.getPivotFields().get("Sales"), "Sum of Sales", SubtotalTypes.Sum);

        // Set style for the pivot table
        pt.setBuiltInStyle(PivotBuiltInStyles.PivotStyleMedium10);

        // Calculate the pivot table data
        pt.calculateData();

        // Add a Slicer to the pivot table
        XlsSlicerCollection slicers = worksheet.getSlicers();
        int index_1 = slicers.add(pt, "F12", 0);

        // Set the name, width, height, and style for the slicer
        XlsSlicer slicer = slicers.get(index_1);
        slicer.setName("Fruit");
        slicer.setWidth(100);
        slicer.setHeight(120);
        slicer.setStyleType(SlicerStyleType.SlicerStyleLight2);

        // Set the cross filter type for the slicer
        XlsSlicerCache slicerCache = (XlsSlicerCache)slicer.getSlicerCache();
        slicerCache.setCrossFilterType(SlicerCacheCrossFilterType.ShowItemsWithNoData);

        // Calculate the pivot table data again
        pt.calculateData();

        // Save the resulting file
        workbook.saveToFile("AddSlicerToPivotTable.xlsx", ExcelVersion.Version2013);
        workbook.dispose();
    }
}

Add Slicers to Pivot Tables in Excel

Update Slicers in Excel

The XlsSlicer class in Spire.XLS for Java provides methods for modifying slicer attributes such as name, caption, style, and cross filter type. 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.getWorksheets().get() method.
  • Get a specific slicer from the worksheet by its index using the Worksheet.getSlicers().get(index) property.
  • Update the properties of the slicer, such as its style, name, caption, and cross filter type using the appropriate methods of the XlsSlicer class.
  • Save the resulting file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
import com.spire.xls.core.spreadsheet.slicer.*;

public class UpdateSlicer {
    public 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.getWorksheets().get(0);

        // Get the first slicer in the worksheet
        XlsSlicer slicer = worksheet.getSlicers().get(0);

        // Change the style, name, and caption for the slicer
        slicer.setStyleType(SlicerStyleType.SlicerStyleDark4);
        slicer.setName("Slicer");
        slicer.setCaption("Slicer");

        // Change the cross filter type for the slicer
        XlsSlicerCache slicerCache = slicer.getSlicerCache();
        slicerCache.setCrossFilterType(SlicerCacheCrossFilterType.ShowItemsWithDataAtTop);

        // Deselect an item in the slicer
        XlsSlicerCacheItemCollection slicerCacheItems = slicerCache.getSlicerCacheItems();
        XlsSlicerCacheItem xlsSlicerCacheItem = slicerCacheItems.get(0);
        xlsSlicerCacheItem.isSelected(false);

        // Save the resulting file
        workbook.saveToFile("UpdateSlicer.xlsx", ExcelVersion.Version2013);
        workbook.dispose();
    }
}

Update Slicers in Excel

Remove Slicers from Excel

Developers can remove a specific slicer from an Excel worksheet using the Worksheet.getSlicers().removeAt() method, or remove all slicers at once using the Worksheet.getSlicers().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.getWorksheets().get() method.
  • Remove a specific slicer from the worksheet by its index using the Worksheet.getSlicers().removeAt() method. Or remove all slicers from the worksheet using the Worksheet.getSlicers().clear() method.
  • Save the resulting file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class RemoveSlicer {
    public 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.getWorksheets().get(0);

        // Remove the first slicer by index
        worksheet.getSlicers().removeAt(0);

        // Alternatively, remove all slicers
        // worksheet.getSlicers().clear();

        // Save the resulting file
        workbook.saveToFile("RemoveSlicer.xlsx", ExcelVersion.Version2013);
        workbook.dispose();
    }
}

Remove Slicers from Excel

Get a Free License

To fully experience the capabilities of Spire.XLS for Java without any evaluation limitations, you can request a free 30-day trial license.

Page 4 of 81
page 4