Spire.Office Knowledgebase Page 27 | E-iceblue

Excel manipulation is a crucial aspect of many modern web applications, from data analysis to report generation. Node.js, with its non-blocking I/O model and rich ecosystem, is an excellent choice for backend development. When combined with Spire.XLS for JavaScript, you can unlock a world of possibilities for handling Excel files efficiently.

This guide will walk you through the process of integrating Spire.XLS for JavaScript into your Node.js projects, covering everything from initial setup to generating a simple Excel document.

Benefits of Using Spire.XLS for JavaScript in Node.js Projects

Node.js is a great option for developing scalable network applications. When paired with Spire.XLS for JavaScript, you get a robust solution for handling Excel files. Here are some key features and benefits of using Spire.XLS for JavaScript in Node.js projects:

  • Comprehensive Excel Support: Spire.XLS for JavaScript supports a wide range of Excel features, including formulas, charts, pivot tables, and more.
  • High Performance: The library is optimized for speed, ensuring that your application remains responsive even when handling large datasets.
  • Cross-Platform Compatibility: With Node.js, you can run your application on any platform that supports JavaScript, including Windows, macOS, and Linux.
  • Secure and Reliable: The library is designed to be secure, with features like data validation and encryption to protect your data.

By leveraging the strengths of both Node.js and Spire.XLS for JavaScript, you can build powerful applications that handle Excel files with ease.

Set Up Your Environment

Step 1

Download and install Node.js from the official website. Make sure to choose the version that matches your operating system.

After the installation is complete, you can verify that Node.js and npm are installed correctly, along with the version numbers, by entering the following commands in CMD:

node -v 
npm -v 

Install Node.js

Step 2

Create a Node.js project in your IntelliJ IDEA.

Create a Node.js project

Install Jest in your project to write and run tests for your code, by running the following command in Terminal:

npm install --save-dev jest

Install jest

Create a JavaScript file named "jest.config.js" in your project, and include the following configuration in it.

module.exports = {
    testTimeout: 20000,
    testEnvironment: 'node',
    transform: {},
    testMatch: ['<rootDir>/*.js'],
    moduleFileExtensions: [ 'json', 'node', 'tsx', 'ts', 'js', 'jsx','mjs'],
};

Configure jest

Add a "fonts" folder and a "lib" folder to your project.

Add folders in Node.js project

Integrate Spire.XLS for JavaScript in Your Project

Download Spire.XLS for JavaScript and unzip it to a location on your disk. Inside the lib folder, you will find the Spire.Xls.Base.js and Spire.Xls.Base.wasm files.

Obtain Spire.XLS for JavaScript library

Copy these two files into the "lib" folder in your Node.js project.

Copy library to Node.js project

Place the font files you plan to use into the "fonts" folder in your project.

Add font files to node.js project

Create and Save Excel Files Using JavaScript

Add a JavaScript file in your project to generate a simple Excel document from JavaScript code.

JavaScript code for creating an Excel file

Here is the entire JavaScript code:

  • JavaScript
// Import the library
const { Module, spirexls } = require("./lib/Spire.Xls.Base.js");

// Define a test case
test('testCase', async () => {
    await new Promise((resolve) => {
        Module.onRuntimeInitialized = () => {
            createExcel();
            resolve();
        };
    });
});

// Create a custom function
function createExcel (){

    // Load fonts
    spirexls.copyLocalPathToVFS("fonts/","/Library/Fonts/");

    // Specify output file name and path
    const outFileName = "HelloWorld.xlsx";
    const outputPath=  "result/" + outFileName;

    // Create a workbook
    let workbook = Module.spirexls.Workbook.Create();

    // Add a sheet
    let sheet =  workbook.Worksheets.Add("MySheet");

    // Write data to a specific cell
    sheet.Range.get("A1").Text = "Hello World";

    // Auto-fit column width
    sheet.Range.get("A1").AutoFitColumns();

    // Save the workbook to a file
    workbook.SaveToFile({fileName:outFileName, version:spirexls.ExcelVersion.Version2016});
    spirexls.copyFileFromFSToLocalStorage(outFileName, outputPath);

    // Dispose resources
    workbook.Dispose();
}

Once you run the code, you will find the generated Excel file in the designated file path.

Excel file generated by JavaScript code.

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.

Enhancing PDF documents with interactive elements has become increasingly important for improving user engagement and functionality. Adding actions to PDFs, such as linking to document pages, executing JavaScript, or triggering a file opening, can significantly elevate the utility of these documents in various professional and personal applications. By incorporating such dynamic features using the Spire.PDF for Java library, developers will be able to unlock new possibilities for their PDF documents, making them more versatile and user-friendly. This article will demonstrate how to add actions to PDF documents with Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you need to add the Spire.Pdf.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 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.pdf</artifactId>
        <version>11.12.16</version>
    </dependency>
</dependencies>

How to Add Actions to PDF using Spire.PDF for Java

Spire.PDF for Java enables developers to add a variety of actions to PDF documents, such as navigation actions, file-open actions, sound actions, and JavaScript actions. Below is a table of classes and their descriptions for commonly used actions:

Class Description
PdfGoToAction Represents an action that navigates to a destination within the current document.
PdfLaunchAction Represents an action that launches and opens a file.
PdfJavaScriptAction Represents an action that executes JavaScript code.
PdfSoundAction Represents an action that plays a sound.

For more action classes and their descriptions, refer to Spire.PDF for Java action API references.

Actions can be added to PDF documents in two primary ways:

1. Using Action Annotations

This method involves creating an action and linking it to an annotation on the page. The action is displayed and triggered when the annotation is clicked.

General Steps:

  • Create a PdfDocument instance and load a PDF document using PdfDocument.LoadFromFile() method.
  • Create an action instance and set its properties.
  • Optionally, draw cue text or images to indicate the action.
  • Create a PdfActionAnnotation instance using the action instance and specify its location on the page.
  • Add the action annotation to the page using PdfPageBase.getAnnotations.add() method.
  • Save the document using PdfDocument.SaveToFile() method.

2. Assigning Actions to Document Events

Actions can also be assigned to document-level events such as opening, closing, or printing the document. These actions are triggered automatically when the specified events occur.

General Steps:

  • Create a PdfDocument instance and load a PDF document using PdfDocument.LoadFromFile() method.
  • Create an action instance and set its properties.
  • Assign the action to a document event using the following methods:
    • PdfDocument.setAfterOpenAction()
    • PdfDocument.setAfterPrintAction()
    • PdfDocument.setAfterSaveAction()
    • PdfDocument.setBeforeCloseAction()
    • PdfDocument.setBeforePrintAction()
    • PdfDocument.setBeforeSaveAction()
  • Save the document using PdfDocument.SaveToFile() method.

Create Navigation Actions in PDF with Java

The PdfGoToAction class can be used to create navigation actions in PDF documents, allowing users to jump to a specific location within the document. Below is a Java code example demonstrating how to create a navigation button in a PDF document.

  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.actions.PdfGoToAction;
import com.spire.pdf.annotations.PdfActionAnnotation;
import com.spire.pdf.general.PdfDestination;
import com.spire.pdf.graphics.PdfBrushes;
import com.spire.pdf.graphics.PdfStringFormat;
import com.spire.pdf.graphics.PdfTextAlignment;
import com.spire.pdf.graphics.PdfTrueTypeFont;

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

public class AddNavigationActionPDF {
    public static void main(String[] args) {
        // Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        // Load a PDF file
        pdf.loadFromFile("Sample.pdf");

        // Create a PdfDestination object
        PdfDestination destination = new PdfDestination(2, new Point2D.Float(0, 0), 0.8f);
        // Create a PdfGoToAction object using the PdfDestination object
        PdfGoToAction goToAction = new PdfGoToAction(destination);

        // Draw a rectangle and the cue text on the first page
        Rectangle2D rect = new Rectangle2D.Float(20, 30, 120, 20);
        pdf.getPages().get(0).getCanvas().drawRectangle(PdfBrushes.getLightGray(), rect);
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 12), true);
        PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center);
        pdf.getPages().get(0).getCanvas().drawString("Click to go to page 2", font, PdfBrushes.getBlack(), rect, format);

        // Create a PdfActionAnnotation object using the PdfGoToAction object
        PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, goToAction);

        // Add the annotation to the first page
        pdf.getPages().get(0).getAnnotations().add(actionAnnotation);

        // Save the document
        pdf.saveToFile("output/PDFNavigationAction.pdf");
        pdf.close();
    }
}

Create Navigation Actions in PDF with Java

Create File-Open Actions in PDF with Java

Developers can use the PdfLaunchAction class to create a file-open action in a PDF document. Below is a Java code example showing how to add a file-open action to a PDF document.

  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.actions.PdfFilePathType;
import com.spire.pdf.actions.PdfLaunchAction;
import com.spire.pdf.annotations.PdfActionAnnotation;
import com.spire.pdf.graphics.PdfBrushes;
import com.spire.pdf.graphics.PdfStringFormat;
import com.spire.pdf.graphics.PdfTextAlignment;
import com.spire.pdf.graphics.PdfTrueTypeFont;

import java.awt.*;
import java.awt.geom.Rectangle2D;

public class AddFileOpenActionPDF {
    public static void main(String[] args) {
        // Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        // Load a PDF file
        pdf.loadFromFile("Sample.pdf");

        // Create a PdfLaunchAction object and set the file path
        PdfLaunchAction launchAction = new PdfLaunchAction("C:/Example.pdf", PdfFilePathType.Absolute);

        // Draw a rectangle and the cue text on the first page
        Rectangle2D rect = new Rectangle2D.Float(20, 30, 120, 20);
        pdf.getPages().get(0).getCanvas().drawRectangle(PdfBrushes.getLightGray(), rect);
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 12), true);
        PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center);
        pdf.getPages().get(0).getCanvas().drawString("Click to open the file", font, PdfBrushes.getBlack(), rect, format);

        // Create a PdfActionAnnotation object using the PdfLaunchAction object
        PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, launchAction);

        // Add the annotation to the first page
        pdf.getPages().get(0).getAnnotations().add(actionAnnotation);

        // Save the document
        pdf.saveToFile("output/PDFFileOpenAction.pdf");
        pdf.close();
    }
}

Create File-Open Actions in PDF with Java

Create Sound Actions in PDF with Java

The PdfSoundAction class is used to handle sound playback in PDF documents, enabling features such as background music and voice reminders. The Java code example below demonstrates how to create sound actions in PDF documents.

  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.actions.PdfSoundAction;
import com.spire.pdf.annotations.PdfActionAnnotation;
import com.spire.pdf.general.PdfSoundChannels;
import com.spire.pdf.general.PdfSoundEncoding;
import com.spire.pdf.graphics.PdfImage;

import java.awt.geom.Rectangle2D;

public class AddSoundActionPDF {
    public static void main(String[] args) {
        // Create an instance of PdfDocument
        PdfDocument pdf = new PdfDocument();

        // Load a PDF file
        pdf.loadFromFile("Sample.pdf");

        // Create a PdfSoundAction object and set the audio property
        PdfSoundAction soundAction = new PdfSoundAction("Music.wav");
        soundAction.setRepeat(false);
        soundAction.getSound().setBits(16);
        soundAction.getSound().setChannels(PdfSoundChannels.Stereo);
        soundAction.getSound().setEncoding(PdfSoundEncoding.Signed);
        soundAction.getSound().setRate(44100);

        // Draw the sound logo on the first page
        PdfImage image = PdfImage.fromFile("Sound.jpg");
        pdf.getPages().get(0).getCanvas().drawImage(image, new Rectangle2D.Float(40, 40, image.getWidth(), image.getHeight()));

        // Create a PdfActionAnnotation object using the PdfSoundAction object at the location of the logo
        Rectangle2D rect = new Rectangle2D.Float(40, 40, image.getWidth(), image.getHeight());
        PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, soundAction);

        // Add the annotation to the first page
        pdf.getPages().get(0).getAnnotations().add(actionAnnotation);

        // Save the document
        pdf.saveToFile("output/PDFSoundAction.pdf");
        pdf.close();
    }
}

Create Sound Actions in PDF with Java

Create JavaScript Actions in PDF with Java

The PdfJavaScript class allows developers to create JavaScript actions within PDF documents, enabling custom interactive features such as creating dynamic forms, validating user input, and automating tasks. The following Java code example demonstrates how to add JavaScript actions to a PDF document.

  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.actions.PdfJavaScript;
import com.spire.pdf.actions.PdfJavaScriptAction;

public class AddJavaScriptActionPDF {
    public static void main(String[] args) {
        // Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        // Load a PDF file
        pdf.loadFromFile("Sample.pdf");

        // Define the JavaScript code and use it to create an instance of PdfJavaScriptAction
        String jsCode = """
                app.alert({
                    cMsg: 'Welcome to the article on The Timeless Delight of Bread!\\n\\nThis article explores the rich history, varieties, and cultural significance of bread. Enjoy your reading!',
                    nIcon: 3,
                    cTitle: 'Document Introduction'
                });
                """;
        PdfJavaScriptAction javaScriptAction = new PdfJavaScriptAction(jsCode);

        // Set the JavaScript action as the action to be executed after opening the PDF file
        pdf.setAfterOpenAction(javaScriptAction);

        // Save the document
        pdf.saveToFile("output/PDFJavaScriptAction.pdf");
        pdf.close();
    }
}

Create JavaScript Actions in PDF with Java

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.

C#: Group Data in Pivot Table in Excel

2024-11-28 01:07:32 Written by Koohji

Grouping data in a pivot table simplifies data analysis by consolidating similar items into meaningful categories. For example, you can group dates into months or years to see trends over time, or group numbers into ranges like price levels or age groups for easier comparison and analysis. In this article, we will demonstrate how to group data in Excel pivot tables based on dates and numbers in C# using Spire.XLS for .NET.

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

Group Pivot Table Data in Excel Based on Dates in C#

The IPivotField.CreateGroup(DateTime start, DateTime end, PivotGroupByTypes[] groupByArray) method in Spire.XLS for .NET allows developers to group data in Excel pivot tables based on date and time. It requires three parameters: a start date time, an end date time, and an array of grouping categories specified by the PivotGroupByTypes enum.

The list below shows the categories that can be used when grouping by date and time:

  • Days
  • Months
  • Quarters
  • Years
  • Seconds
  • Minutes
  • Hours

The steps below demonstrate how to group the data in a pivot table by date and time using Spire.XLS for .NET:

  • Create an instance of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Access the worksheet that contains the pivot table using the Workbook.Worksheets[] property.
  • Get the pivot table using the Worksheet.PivotTables[] property.
  • Get the specific pivot field that you want to group using the XlsPivotTable.PivotFields[] property.
  • Create two instances of the DateTime class to specify the start date time and end date time.
  • Create a PivotGroupByTypes array to specify the grouping categories, such as days and months.
  • Group the data of the selected pivot field based on the specified grouping categories using the IPivotField.CreateGroup(DateTime start, DateTime end, PivotGroupByTypes[] groupByArray) method.
  • Refresh the pivot table using the XlsPivotTable.IsRefreshOnLoad property.
  • Save the result file using the Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.PivotTables;
using System;

namespace GroupDataInPivotTableByDates
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the Workbook class
            Workbook workbook = new Workbook();
            // Load an Excel file
            workbook.LoadFromFile("Sample1.xlsx");

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Get the first pivot table in the worksheet
            XlsPivotTable pt = sheet.PivotTables[0] as XlsPivotTable;

            // Get the "Date" pivot field 
            PivotField ptField = pt.PivotFields["Date"] as PivotField;
            // Specify the start date time and end date time
            DateTime start = new DateTime(2024, 1, 1);
            DateTime end = new DateTime(2024, 10, 14);

            // Create a PivotGroupByTypes array to specify the grouping categories, such as days and months
            PivotGroupByTypes[] groupByTypes = new PivotGroupByTypes[]
            {
                PivotGroupByTypes.Days,
                PivotGroupByTypes.Months
            };

            // Group the data in the pivot field based on the specified grouping categories
            ptField.CreateGroup(start, end, groupByTypes);

            // Refresh the pivot table
            pt.Cache.IsRefreshOnLoad = true;

            // Save the result file
            workbook.SaveToFile("GroupPivotTableDataByDates.xlsx", FileFormat.Version2016);
            workbook.Dispose();
        }
    }
}

Group Pivot Table Data in Excel Based on Dates in C#

Group Pivot Table Data in Excel Based on Numbers in C#

In addition to grouping based on date and time, Spire.XLS for .NET also enables developers to group pivot table data based on numeric values using another overload of the CreateGroup() method: CreateGroup(double startValue, double endValue, double intervalValue). The detailed steps are as follows.

  • Create an instance of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Access the worksheet that contains the pivot table using the Workbook.Worksheets[] property.
  • Get the pivot table using the Worksheet.PivotTables[] property.
  • Get the specific pivot field that you want to group using the XlsPivotTable.PivotFields[] property.
  • Group the data in the selected pivot field based on numeric values using the IPivotField.CreateGroup(double startValue, double endValue, double intervalValue) method.
  • Calculate the pivot table data using the XlsPivotTable.CalculateData() method.
  • Refresh the pivot table using the XlsPivotTable.IsRefreshOnLoad property.
  • Save the result file using the Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.PivotTables;

namespace GroupDataInPivotTableByNumbers
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the Workbook class
            Workbook workbook = new Workbook();
            // Load an Excel file
            workbook.LoadFromFile("Sample2.xlsx");

            // Get the first worksheet
            Worksheet pivotSheet = workbook.Worksheets[0];

            // Get the first pivot table in the worksheet
            XlsPivotTable pt = pivotSheet.PivotTables[0] as XlsPivotTable;

            // Group data of the "SalesAmount" pivot field based on based on numeric values
            PivotField ptField = pt.PivotFields["SalesAmount"] as PivotField;
            ptField.CreateGroup(1500, 4500, 200);

            // Calculate the pivot table data
            pt.CalculateData();
            // Refresh the pivot table
            pt.Cache.IsRefreshOnLoad = true;

            // Save the result file
            workbook.SaveToFile("GroupPivotTableDataByNumbers.xlsx", FileFormat.Version2016);
            workbook.Dispose();
        }
    }
}

Group Pivot Table Data in Excel Based on Numbers in C#

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.

page 27