Spire.Office Knowledgebase Page 13 | E-iceblue

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>15.11.3</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.

Microsoft Excel is a powerful tool for data management; however, its proprietary format can pose challenges for sharing and integrating data into web workflows. In contrast, Markdown is a lightweight and widely supported markup language that simplifies text formatting for documentation, wikis, and platforms like GitHub.

By converting Excel files to Markdown, you can seamlessly incorporate structured data into technical documents, READMEs, and static websites. This article will guide you through the steps to programmatically convert Excel files to Markdown format using C# and the Spire.XLS for .NET library.

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

Convert an Excel XLS or XLSX File to Markdown in C#

Developers can effortlessly convert Excel XLS or XLSX files to Markdown files by using the Workbook.SaveToMarkdown() method provided by Spire.XLS for .NET. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load a sample Excel XLS or XLSX file into the Workbook object using the Workbook.LoadFromFile() method.
  • Save the Excel file as a Markdown file using the Workbook.SaveToMarkdown() method.
  • C#
using Spire.Xls;

namespace ConvertExcelToMarkdown
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an object of the Workbook class
            Workbook workbook = new Workbook();
            // Load a sample Excel XLS file
            //workbook.LoadFromFile("Sample.xls");
            // Load a sample Excel XLSX file
            workbook.LoadFromFile("Sample.xlsx");

            // Save the Excel file as a Markdown file
            workbook.SaveToMarkdown("output.md");
            // Release the resources used by the Workbook object
            workbook.Dispose();
        }
    }
}

Convert Excel to Markdown in C#

Get a Free License

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

Creating dynamic documents is essential for many applications. This guide will explore how to generate a Word document using Spire.Doc for JavaScript within a React environment. We will cover the essential features needed for effective document creation, including adding titles, headings, and paragraphs to structure your content effectively.

You'll also learn how to enhance your documents by incorporating images, creating lists for organized information, and adding tables to present data clearly. By the end of this tutorial, you'll be equipped with the skills to produce professional documents directly from your React applications.

Install Spire.Doc for JavaScript

To get started with creating Word documents 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 Titles, Headings, and Paragraphs to Word in React

To add a title, headings, and paragraphs to a Word document, you primarily utilize the Document and Section classes provided by Spire.Doc for JavaScript. The AddParagraph() method creates new paragraphs, while AppendText() allows you to insert text into those paragraphs.

Paragraphs can be formatted using built-in styles (e.g., Title, Heading 1-4) for consistent structure, or customized with specific fonts, sizes, and colors through user-defined styles for tailored document design.

Steps for adding titles, headings, and parargraphs to a Word documents in React:

  • Import the necessary font files into the virtual file system (VFS).
  • Create a Document object using wasmModule.Document.Create().
  • Include a new section in the document with Document.AddSection().
  • Add paragraphs to the document using Section.AddParagraph().
  • Use Paragraph.ApplyStyle() to apply built-in styles (Title, Heading1, Heading2, Heading3) to specific paragraphs.
  • Define a custom paragraph style with wasmModule.ParagraphStyle.Create() and apply it to a designated paragraph.
  • Save the document as a DOCX file and initiate the 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 spiredoc 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 to add text to word
  const AddText = async () => {
    if (wasmModule) {

      // Load the font files into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('times.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbd.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      
      // Create a new document
      const doc= wasmModule.Document.Create();

      // Add a section
      let section = doc.AddSection();

      // Set page margins
      section.PageSetup.Margins.All = 60;

      // Add a title paragraph
      let title_para = section.AddParagraph();
      title_para.AppendText('This is title');
      title_para.ApplyStyle({builtinStyle: wasmModule.BuiltinStyle.Title});

      // Add heading paragraphs
      let heading_one = section.AddParagraph();
      heading_one.AppendText('This is heading 1');
      heading_one.ApplyStyle({builtinStyle: wasmModule.BuiltinStyle.Heading1});

      let heading_two = section.AddParagraph();
      heading_two.AppendText('This is heading 2');
      heading_two.ApplyStyle({builtinStyle: wasmModule.BuiltinStyle.Heading2});

      let heading_three = section.AddParagraph();
      heading_three.AppendText('This is heading 3');
      heading_three.ApplyStyle({builtinStyle: wasmModule.BuiltinStyle.Heading3});

      let heading_four = section.AddParagraph();
      heading_four.AppendText('This is heading 4');
      heading_four.ApplyStyle({builtinStyle: wasmModule.BuiltinStyle.Heading4});

      // Add a normal paragraph
      let normal_para = section.AddParagraph();
      normal_para.AppendText('This is a paragraph.');

      // Create a paragraph style,specifying font name, font size, and text color
      let paragraph_style = wasmModule.ParagraphStyle.Create(doc);
      paragraph_style.Name = 'newStyle';
      paragraph_style.CharacterFormat.FontName = 'Times New Roman'
      paragraph_style.CharacterFormat.FontSize = 13;
      paragraph_style.CharacterFormat.TextColor = wasmModule.Color.get_Blue();

      // Add the style to the document
      doc.Styles.Add(paragraph_style);

      // Apply the style to the paragraph
      normal_para.ApplyStyle(paragraph_style.Name);

      // Save the document
      const outputFileName = 'output.docx';
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
 
      // Create a Blob for the downloaded file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
      const url = URL.createObjectURL(modifiedFile);

      // Trigger file 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 Text to a Word Document in React</h1>
      <button onClick={AddText} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Click "Generate", and a "Save As" window will appear, prompting you to save the output file in your chosen folder.

React app to create a Word document

Below is a screenshot of the generated Word file that includes a title, several headings, and a normal paragraph:

Add text to a Word document in React

Add an Image to Word in React

Inserting images into a Word document involves using the AppendPicture() method, which allows you to add a picture to a specific paragraph. The process begins by loading the image file into the virtual file system (VFS), ensuring that the image is accessible for insertion.

Steps for adding an image to a Word doucment in React:

  • Load an image file into the virtual file system (VFS).
  • Create a Document object using wasmModule.Document.Create().
  • Add a new section to the document with Document.AddSection().
  • Insert a new paragraph in the section using Section.AddParagraph().
  • Use the Paragraph.AppendPicture() method to add the loaded image to the paragraph.
  • Save the document as a DOCX file and trigger the 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 spiredoc 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 to add image to word
  const AddImage = async () => {
    if (wasmModule) {

      // Load an image file into the virtual file system (VFS)
      const inputImageFile = 'logo.png';
      await wasmModule.FetchFileToVFS(inputImageFile, '', `${process.env.PUBLIC_URL}/`);

      // Create a new document
      const doc= wasmModule.Document.Create();

      // Add a section
      let section = doc.AddSection();

      // Set page margins
      section.PageSetup.Margins.All = 60;

      // Add a paragraph 
      let image_para = section.AddParagraph();

      // Add an image to the paragraph
      image_para.AppendPicture({imgFile: inputImageFile});

      // Save the document
      const outputFileName = 'output.docx';
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
 
      // Create a Blob for the downloaded file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
      const url = URL.createObjectURL(modifiedFile);

      // 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 to a Word Document in React

); } export default App;

Add an image to a Word document in React

Add a List to Word in React

To create lists in your Word document, utilize the ListStyle class to define the appearance of your lists, such as bulleted or numbered formats. The ApplyStyle() method associates paragraphs with the defined list style, enabling consistent formatting across multiple items.

Steps for adding a list to a Word document in React:

  • Load the required font files into the virtual file system (VFS).
  • Create a Document object using wasmModule.Document.Create().
  • Add a section to the document with Document.AddSection().
  • Define a list style using wasmModule.ListStyle.Create().
  • Insert several paragraphs in the section using Section.AddParagraph().
  • Apply the defined list style to the paragraphs using Paragraph.ListFormat.ApplyStyle().
  • Save the document as a DOCX file and trigger the 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 spiredoc 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 to add list to word
  const AddList = async () => {
    if (wasmModule) {

      // Load the font files into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('times.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbd.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      
      // Create a new document
      const doc= wasmModule.Document.Create();

      // Add a section
      let section = doc.AddSection();

      // Set page margins
      section.PageSetup.Margins.All = 60;

      // Define a bullet list style
      let list_style = wasmModule.ListStyle.Create(doc, wasmModule.ListType.Bulleted);
      list_style.Name = 'bulletedList';
      list_style.Levels.get_Item(0).BulletCharacter = '\u00B7';
      list_style.Levels.get_Item(0).CharacterFormat.FontName = 'Symbol';
      list_style.Levels.get_Item(0).CharacterFormat.FontSize = 14;
      list_style.Levels.get_Item(0).TextPosition = 20;

      // Add the list style to the document
      doc.ListStyles.Add(list_style);

      // Add title paragraph
      let paragraph = section.AddParagraph();
      let text_range = paragraph.AppendText('Fruits:');
      paragraph.Format.AfterSpacing = 5;
      text_range.CharacterFormat.FontName = 'Times New Roman'
      text_range.CharacterFormat.FontSize = 14;

      // Add items to the bullet list
      const fruits = ['Apple', 'Banana', 'Watermelon', 'Mango'];
      fruits.forEach(fruit => {
        paragraph = section.AddParagraph();
        let text_range = paragraph.AppendText(fruit);
        paragraph.ListFormat.ApplyStyle(list_style.Name);
        paragraph.ListFormat.ListLevelNumber = 0;
        text_range.CharacterFormat.FontName = 'Times New Roman'
        text_range.CharacterFormat.FontSize = 14;
      });

      // Save the document
      const outputFileName = 'output.docx';
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
 
      // Create a Blob for the downloaded file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
      const url = URL.createObjectURL(modifiedFile);

      // Trigger file 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 Lists to a Word Document in React</h1>
      <button onClick={AddList} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Add a list to a Word document in React

Add a Table to Word in React

To create tables, use the AddTable() method where you can specify the number of rows and columns with ResetCells(). Once the table is created, you can populate individual cells by using the AddParagraph() and AppendText() methods to insert text content. Additionally, the AutoFit() method can be employed to automatically adjust the table layout based on its contents, ensuring a clean and organized presentation of your data.

Steps for adding a table to a Word document in React:

  • Load the required font files into the virtual file system (VFS).
  • Create a Document object using wasmModule.Document.Create().
  • Add a section to the document with Document.AddSection().
  • Create a two-dimensional array to hold the table data, including headers and values.
  • Use Section.AddTable() to create a table, specifying visibility options like borders.
  • Call Table.ResetCells() to define the number of rows and columns in the table based on your data.
  • Iterate through the data array, adding text to each cell using the TableCell.AddParagraph() and Paragraph.AppendText() methods.
  • Use the Table.AutoFit() method to adjust the table size according to the content.
  • Save the document as a DOCX file and trigger the 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 spiredoc 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 to add table to word
  const AddTable = async () => {
    if (wasmModule) {

      // Load the font files into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('times.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbd.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      
      // Create a new document
      const doc= wasmModule.Document.Create();

      // Add a section
      let section = doc.AddSection();

      // Set page margins
      section.PageSetup.Margins.All = 60;

      // Define table data
      let data =
        [
            ['Product', 'Unit Price', 'Quantity', 'Sub Total'],
            ['A', '$29', '120', '$3,480'],
            ['B', '$35', '110', '$3,850'],
            ['C', '$68', '140', '$9,520'],
        ];

      // Add a table
      let table = section.AddTable({showBorder: true});

      // Set row number and column number
      table.ResetCells(data.length , data[0].length);

      // Write data to cells
      for (let r = 0; r < data.length; r++) {
        let data_row = table.Rows.get(r);
        data_row.Height = 20;
        data_row.HeightType = wasmModule.TableRowHeightType.Exactly;
        data_row.RowFormat.BackColor = wasmModule.Color.Empty();
        for (let c = 0; c < data[r].length; c++) {

            let cell = data_row.Cells.get(c);
            cell.CellFormat.VerticalAlignment = wasmModule.VerticalAlignment.Middle;
            let text_range = cell.AddParagraph().AppendText(data[r][c]);
            text_range.CharacterFormat.FontName = 'Times New Roman'
            text_range.CharacterFormat.FontSize = 14;
        }
      }

      // Automatically fit the table to the cell content
      table.AutoFit(wasmModule.AutoFitBehaviorType.AutoFitToContents);

      // Save the document
      const outputFileName = 'output.docx';
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
 
      // Create a Blob for the downloaded file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
      const url = URL.createObjectURL(modifiedFile);

      // Trigger file 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 Tables to a Word Document in React</h1>
      <button onClick={AddTable} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Add a table to a Word document in React

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.

page 13