Java: Extract Tables from Word Documents

2025-01-24 06:34:18 Written by Koohji

Extracting tables from Word documents is essential for many applications, as they often contain critical data for analysis, reporting, or system integration. By automating this process with Java, developers can create robust applications that seamlessly access this structured data, enabling efficient conversion into alternative formats suitable for databases, spreadsheets, or web-based visualizations. This article will demonstrate how to use Spire.Doc for Java to efficiently extract tables from Word documents in Java programs.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.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.doc</artifactId>
        <version>14.10.6</version>
    </dependency>
</dependencies>

Extract Tables from Word Documents with Java

With Spire.Doc for Java, developers can extract tables from Word documents using the Section.getTables() method. Table data can be accessed by iterating through rows and cells. The process for extracting tables is detailed below:

  • Create a Document object.
  • Load a Word document using the Document.loadFromFile() method.
  • Access the sections in the document using the Document.getSections() method and iterate through them.
  • Access the tables in each section using the Section.getTables() method and iterate through them.
  • Access the rows in each table using the Table.getRows() method and iterate through them.
  • Access the cells in each row using the TableRow.getCells() method and iterate through them.
  • Retrieve text from each cell by iterating through its paragraphs using the TableCell.getParagraphs() and Paragraph.getText() methods.
  • Add the extracted table data to a StringBuilder object.
  • Write the StringBuilder object to a text file or use it as needed.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;

import java.io.FileWriter;
import java.io.IOException;

public class ExtractWordTable {
    public static void main(String[] args) {
        // Create a Document object
        Document doc = new Document();

        try {
            // Load a Word document
            doc.loadFromFile("Sample.docx");

            // Iterate the sections in the document
            for (int i = 0; i < doc.getSections().getCount(); i++) {
                // Get a section
                Section section = doc.getSections().get(i);
                // Iterate the tables in the section
                for (int j = 0; j < section.getTables().getCount(); j++) {
                    // Get a table
                    Table table = section.getTables().get(j);
                    // Collect all table content
                    StringBuilder tableText = new StringBuilder();
                    for (int k = 0; k < table.getRows().getCount(); k++) {
                        // Get a row
                        TableRow row = table.getRows().get(k);
                        // Iterate the cells in the row
                        StringBuilder rowText = new StringBuilder();
                        for (int l = 0; l < row.getCells().getCount(); l++) {
                            // Get a cell
                            TableCell cell = row.getCells().get(l);
                            // Iterate the paragraphs to get the text in the cell
                            String cellText = "";
                            for (int m = 0; m < cell.getParagraphs().getCount(); m++) {
                                Paragraph paragraph = cell.getParagraphs().get(m);
                                cellText += paragraph.getText() + " ";
                            }
                            if (l < row.getCells().getCount() - 1) {
                                rowText.append(cellText).append("\t");
                            } else {
                                rowText.append(cellText).append("\n");
                            }
                        }
                        tableText.append(rowText);
                    }

                    // Write the table text to a file using try-with-resources
                    try (FileWriter writer = new FileWriter("output/Tables/Section-" + (i + 1) + "-Table-" + (j + 1) + ".txt")) {
                        writer.write(tableText.toString());
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Extract Word Tables to Text with Java

Extract Tables from Word Documents to Excel Worksheets

Developers can use Spire.Doc for Java with Spire.XLS for Java to extract table data from Word documents and write it to Excel worksheets. To get started, download Spire.XLS for Java or add the following Maven configuration:

<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>

The detailed steps for extracting tables from Word documents to Excel workbooks are as follows:

  • Create a Document object.
  • Create a Workbook object and remove the default worksheets using the Workbook.getWorksheets().clear() method.
  • Load a Word document using the Document.loadFromFile() method.
  • Access the sections in the document using the Document.getSections() method and iterate through them.
  • Access the tables in each section using the Section.getTables() method and iterate through them.
  • Create a worksheet for each table using the Workbook.getWorksheets().add() method.
  • Access the rows in each table using the Table.getRows() method and iterate through them.
  • Access the cells in each row using the TableRow.getCells() method and iterate through them.
  • Retrieve text from each cell by iterating through its paragraphs using the TableCell.getParagraphs() and Paragraph.getText() methods.
  • Write the extracted cell text to the corresponding cell in the worksheet using the Worksheet.getRange().get(row, column).setValue() method.
  • Format the worksheet as needed.
  • Save the workbook to an Excel file using the Workbook.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ExtractWordTableToExcel {
    public static void main(String[] args) {
        // Create a Document object
        Document doc = new Document();

        // Create a Workbook object
        Workbook workbook = new Workbook();
        // Remove the default worksheets
        workbook.getWorksheets().clear();

        try {
            // Load a Word document
            doc.loadFromFile("Sample.docx");

            // Iterate the sections in the document
            for (int i = 0; i < doc.getSections().getCount(); i++) {
                // Get a section
                Section section = doc.getSections().get(i);
                // Iterate the tables in the section
                for (int j = 0; j < section.getTables().getCount(); j++) {
                    // Get a table
                    Table table = section.getTables().get(j);
                    // Create a worksheet for each table
                    Worksheet sheet = workbook.getWorksheets().add("Section-" + (i + 1) + "-Table-" + (j + 1));
                    for (int k = 0; k < table.getRows().getCount(); k++) {
                        // Get a row
                        TableRow row = table.getRows().get(k);
                        for (int l = 0; l < row.getCells().getCount(); l++) {
                            // Get a cell
                            TableCell cell = row.getCells().get(l);
                            // Iterate the paragraphs to get the text in the cell
                            String cellText = "";
                            for (int m = 0; m < cell.getParagraphs().getCount(); m++) {
                                Paragraph paragraph = cell.getParagraphs().get(m);
                                if (m > 0 && m < cell.getParagraphs().getCount() - 1) {
                                    cellText += paragraph.getText() + "\n";
                                }
                                else {
                                    cellText += paragraph.getText();
                                }
                                // Write the cell text to the corresponding cell in the worksheet
                                sheet.getRange().get(k + 1, l + 1).setValue(cellText);
                            }
                            // Auto-fit columns
                            sheet.autoFitColumn(l + 1);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        workbook.saveToFile("output/WordTableToExcel.xlsx", FileFormat.Version2016);
    }
}

Extract Tables from Word Documents to Excel Worksheets 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.

Converting between Word and TXT formats is a skill that can greatly enhance your productivity and efficiency in handling documents. For example, converting a Word document to a plain text file can make it easier to analyze and manipulate data using other text processing tools or programming languages. Conversely, converting a text file to Word format allows you to add formatting, graphics, and other elements to enhance the presentation of the content. In this article, you will learn how to convert text files to Word format or convert Word files to text format in React using Spire.Doc for JavaScript.

Install Spire.Doc for JavaScript

To get started with the conversion between the TXT and Word formats in a React application, you can either download Spire.Doc for JavaScript from our website or install it via npm with the following command:

Copy
npm i spire.office

The downloaded product package integrates Spire.Doc for JavaScript, Spire.XLS for JavaScript, Spire.PDF for JavaScript, and Spire.Presentation for JavaScript. To use the features of Spire.Doc for JavaScript, you need to copy the corresponding files (spire.doc.js, Spire.Doc.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and the _framework folder) to the public folder of your project. To ensure proper text rendering, you can add relevant font files with a custom path. In the following example, the font is added to the path: public\static\font.

For more details, refer to the documentation: How to Integrate Spire.Doc for JavaScript in a React Project

Convert Text (TXT) to Word in JavaScript

Spire.Doc for JavaScript allows you to load a TXT file and then save it to Word Doc or Docx format using the Document.SaveToFile() method. The following are the main steps.

  • Create a new document using the new wasmModule.Document() method.
  • Load a text file using the Document.LoadFromFile() method.
  • Save the text file as a Word document using the Document.SaveToFile() method.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';

function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.Doc
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
        const rawModule = spireModule.default || spireModule;
        window.wasmModule = typeof rawModule === 'function'
          ? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
          : rawModule;
        setWasmModule(window.wasmModule);
      } catch (error) {
        console.error('Failed to load spire.doc.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert a text file to a Word document
  const TXTtoWord = async () => {
    const wasmModule = window.wasmModule.spiredoc;

    if (wasmModule) {
      // Load the font files into the virtual file system (VFS)
      await window.spire.FetchFileToVFS('CALIBRI.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Specify the input file name and the output file name
      const inputFileName = 'input.txt';
      const outputFileName = 'TxtToWord.docx';

      // Fetch the input file and add it to the VFS
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create an instance of the Document class
      const doc = new wasmModule.Document();

      // Load the text file
      doc.LoadFromFile(inputFileName);

      // Save the text file as a Word document 
      doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2016 });

      // Read the generated Word document from VFS
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);

      // Create a Blog object from the Word document
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });

      // Create a URL for the Blob
      const url = URL.createObjectURL(modifiedFile);

      // Create an anchor element to trigger the download
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);

      // Clean up resources
      doc.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Text to Word Using JavaScript in React</h1>
      <button onClick={TXTtoWord} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to download the Word document converted from a TXT file:

Run the React app at localhost:3000

Below is the input text file and the generated Word document:

Convert a TXT file to a Word document

Convert Word to Text (TXT) in JavaScript

The Document.SaveToFile() method can also be used to export a Word Doc or Docx document to a plain text file. The following are the main steps.

  • Create a new document using the new wasmModule.Document() method.
  • Load a Word document using the Document.LoadFromFile() method.
  • Save the Word document in TXT format using the Document.SaveToFile({fileName: string, fileFormat: wasmModule.FileFormat.Txt}) method.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';

function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.Doc
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
        const rawModule = spireModule.default || spireModule;
        window.wasmModule = typeof rawModule === 'function'
          ? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
          : rawModule;
        setWasmModule(window.wasmModule);
      } catch (error) {
        console.error('Failed to load spire.doc.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert a Word document to a text file
  const WordToTXT = async () => {
    const wasmModule = window.wasmModule.spiredoc;

    if (wasmModule) {
      // Load the font files into the virtual file system (VFS)
      await window.spire.FetchFileToVFS('CALIBRI.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Specify the input file name and the output file name
      const inputFileName = 'Data.docx';
      const outputFileName = 'WordToText.txt';

      // Fetch the input file and add it to the VFS
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create an instance of the Document class
      const doc = new wasmModule.Document();

      // Load the Word document
      doc.LoadFromFile(inputFileName);

      // Save the Word document in TXT format
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Txt});

      // Read the generated text file from VFS
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);

      // Create a Blog object from the text file
      const modifiedFile = new Blob([modifiedFileArray], {type: 'text/plain'});

      // Create a URL for the Blob
      const url = URL.createObjectURL(modifiedFile);

      // Create an anchor element to trigger the download
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

      // Clean up resources
      doc.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert a Word Document to Plain Text Using JavaScript in React</h1>
      <button onClick={WordToTXT} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Convert a Word document to a text file

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.

In Word documents, hyperlinks can be added to images and shapes to link to external websites, files, or specific sections within the document. However, over time, the destination URLs or file paths may change due to updates in external resources or reorganization of the document. When this happens, it’s important to update the hyperlinks to ensure they continue to point to the correct locations. For example, if a website's URL changes, an image is moved to a new folder or a linked shape needs to connect to a different page, updating the hyperlinks is crucial to keep the document functional and user-friendly.

In this article, we will introduce how to programmatically update hyperlinks for images and shapes in Word documents in C# using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc 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.Doc

Update Hyperlinks for Images in Word in C#

Spire.Doc for .NET offers the DocPicture.HasHyperlink property which allows you to identify if an image contains a hyperlink. Once identified, you can use the DocPicture.HRef property to seamlessly update or modify the hyperlink as needed. The detailed steps are as follows.

  • Create an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile() method.
  • Iterate through all sections in the document, all paragraphs in each section, and all objects in each paragraph.
  • Check if the object is a DocPicture.
  • Check if the DocPicture object has a hyperlink using the DocPicture.HasHyperlink property.
  • Modify the hyperlink of the DocPicture object using the DocPicture.HRef property.
  • Save the modified document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace UpdateHyperlinkForImage
{
    internal class Program
    {
        static void Main(string[] args) 
        {       
            // Create a Document instance
            Document doc = new Document();
            // Load a Word document
            doc.LoadFromFile("Sample1.docx");

            // Iterate through all sections in the document
            foreach (Section section in doc.Sections)
            {
                // Iterate through all paragraphs in the section
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    // Iterate through all objects in the paragraph
                    foreach (DocumentObject documentObject in paragraph.ChildObjects)
                    {
                        // Check if the object is a DocPicture (image)
                        if (documentObject is DocPicture)
                        {
                            DocPicture pic = documentObject as DocPicture;
                            // Check if the DocPicture object has a hyperlink
                            if (pic.HasHyperlink)
                            {
                                // Update the hyperlink (if you want to remove the hyperlink, set the value to null) 
                                pic.HRef = "https://www.e-iceblue.com/";

                            }
                        }
                    }
                }
            }

            // Save the modified document
            doc.SaveToFile("UpdateImageHyperlink.docx", FileFormat.Docx2016);
            doc.Close();
        }
    }
}

Update Hyperlinks for Images in Word in C#

Update Hyperlinks for Shapes in Word in C#

Similarly, you can check if a shape has a hyperlink using the ShapeObject.HasHyperlink property, and update or modify the hyperlink with the ShapeObject.HRef property. The detailed steps are as follows.

  • Create an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile() method.
  • Iterate through all sections in the document, all paragraphs in each section, and all objects in each paragraph.
  • Check if the object is a ShapeObject.
  • Check if the ShapeObject object has a hyperlink using the ShapeObject.HasHyperlink property.
  • Modify the hyperlink of the ShapeObject object using the ShapeObject.HRef property.
  • Save the modified document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace UpdateHyperlinkForShape
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Document instance
            Document doc = new Document();
            // Load a Word document
            doc.LoadFromFile("Sample2.docx");

            // Iterate through all sections in the document
            foreach (Section section in doc.Sections)
            {
                // Iterate through all paragraphs in the section
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    // Iterate through all objects in the paragraph
                    foreach (DocumentObject documentObject in paragraph.ChildObjects)
                    {
                        // Check if the object is a ShapeObject
                        if (documentObject is ShapeObject)
                        {
                            ShapeObject shape = documentObject as ShapeObject;
                            // Check if the shape has a hyperlink
                            if (shape.HasHyperlink)
                            {
                                // Update the hyperlink (if you want to remove the hyperlink, set the value to null) 
                                shape.HRef = "https://www.e-iceblue.com/";
                            }
                        }
                    }
                }
            }

            // Save the modified document
            doc.SaveToFile("UpdateShapeHyperlink.docx", FileFormat.Docx2016);
            doc.Close();
        }
    }
}

Update Hyperlinks for Shapes in Word 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 65