Java (483)

Plain text (.txt) files are simple and widely used, but they lack formatting and structure. If you need to enhance a TXT file with headings, fonts, tables, or images, converting it to a Word (.docx) file is a great solution.
In this tutorial, you'll learn how to convert a .txt file to a .docx Word document in Java using Spire.Doc for Java — a powerful library for Word document processing.
Why choose Spire.Doc for Java:
- The converted Word document preserves the line breaks and content from the TXT file.
- You can further modify fonts, add styles, or insert images using Spire.Doc's rich formatting APIs.
- Supported various output formats, including converting Word to PDF, Excel, TIFF, PostScript, etc.
Prerequisites
To convert TXT to Word with Spire.Doc for Java smoothly, you should download it from its official download page and add the Spire.Doc.jar file as a dependency in your Java program.
If you are using 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.doc</artifactId>
<version>13.6.2</version>
</dependency>
</dependencies>
Steps to Convert TXT to Word in Java
Now let's take a look at how to implement it in code. With Spire.Doc for Java, the process is straightforward. You can complete the conversion with just a few lines — no need for manual formatting or additional dependencies.
To help you better understand the code:
- Document is the core class that acts as an in-memory representation of a Word document.
- loadFromFile() uses internal parsers to read .txt content and wrap it into a single Word section with default font and margins.
- When saveToFile() is called, Spire.Doc automatically converts the plain text into a .docx file by generating a structured Word document in the OpenXML format.
Below is a step-by-step code example to help you get started quickly:
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class ConvertTextToWord {
public static void main(String[] args) {
// Create a Text object
Document txt = new Document();
// Load a Word document
txt.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.txt");
// Save the document to Word
txt.saveToFile("ToWord.docx", FileFormat.Docx);
// Dispose resources
doc.dispose();
}
}
RESULT:

Tip:
After converting TXT files to DOC/DOCX, you can further customize the document's formatting as needed. To simplify this process, Spire.Doc for Java provides built-in support for editing text properties such as changing font color, inserting footnote, adding text and image watermark, etc.
How to Convert Word to TXT with Java
Except for TXT to Word conversion, Spire.Doc for Java also supports converting DOC/DOCX files to TXT format, making it easy to extract plain text from richly formatted Word documents. This functionality is especially useful when you need to strip out styling and layout to work with clean, raw content — such as for text analysis, search indexing, archiving, or importing into other systems that only support plain text.
Simply copy the code below and run the code to manage conversion:
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class ConvertWordtoText {
public static void main(String[] args) {
// Create a Doc object
Document doc = new Document();
// Load a Word document
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.doc");
// Save the document to Word
doc.saveToFile("ToText.txt", FileFormat.Txt);
// Dispose resources
doc.dispose();
}
}
RESULT:

Get a Free License
To remove evaluation watermarks and unlock full features, you can request a free 30-day license.
Conclusion
With Spire.Doc for Java, converting TXT to Word is fast, accurate, and doesn't require Microsoft Word to be installed. This is especially useful for Java developers working on reporting, document generation, or file conversion tools. Don't hesitate and give it a try now.

Barcodes are widely used in various industries for inventory management, retail, logistics, and more. Reading barcodes efficiently is crucial for automating data entry and improving accuracy. In Java, one of the most reliable libraries for barcode recognition is Spire.Barcode for Java. This article provides a comprehensive guide on how to read barcode in Java using this powerful library.
Table of Contents
- Introduction to Spire.Barcode for Java
- Key Features of Spire.Barcode
- Setting Up Spire.Barcode in Your Java Project
- Reading a Single Barcode from an Image File
- Reading Multiple Barcodes from One Image
- Customizing Barcode Recognition Settings
- Conclusion
- FAQs
Introduction to Spire.Barcode for Java
Spire.Barcode for Java is a robust library designed to generate and read barcodes in Java applications. It supports a wide range of barcode symbologies, including:
- 1D Barcodes : Code 128, Code 39, EAN-13, UPC-A, etc.
- 2D Barcodes : QR Code, DataMatrix, PDF417, etc.
Spire.Barcode provides fast and precise barcode recognition in Java, whether scanning from a dedicated barcode image or a complex image containing additional elements.
Key Features of Spire.Barcode
Before diving into implementation, let’s explore some key features of Spire.Barcode:
- Multi-Format Support : Read barcodes from PNG, JPG, BMP, GIF, and TIFF images.
- Batch Processing : Scan multiple barcodes in a single image.
- High Recognition Accuracy : Advanced algorithms ensure reliable barcode detection.
- Customizable Settings : Adjust scan regions and barcode types for optimized recognition.
- Cross-Platform Compatibility : Works seamlessly on Windows, Linux, and macOS.
These features make Spire.Barcode an excellent choice for enterprise-level barcode processing.
Setting Up Spire.Barcode in Your Java Project
To start reading barcodes in Java, you need to integrate Spire.Barcode into your project. Follow these steps:
Step 1: Install the Library
If you're using Maven, you can easily integrate Spire.Barcode by adding the following dependency to 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>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.barcode</artifactId>
<version>5.1.11</version>
</dependency>
For manual setup, download Spire.Barcode for Java from our website and add the downloaded .jar file to your project’s build path.
Step 2: Get a Temporary License
Spire.Barcode requires a license to read certain barcode types. To unlock full barcode recognition capabilities, get a free 30-day trial license. After receiving the license file, apply it using this code:
LicenseProvider.setLicenseKey("your license key");
Now, you're ready to read barcode in Java using Spire.Barcode.
Reading a Single Barcode from an Image File
Reading one barcode from an image is a fundamental scenario, and Spire.Barcode facilitates this with just a few lines of code.
Here’s a step-by-step example:
import com.spire.barcode.BarcodeScanner;
import com.spire.barcode.license.LicenseProvider;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ReadBarcode {
public static void main(String[] args) throws IOException {
// Apply license key to remove restrictions on barcode types
LicenseProvider.setLicenseKey("your license key");
// Load the image file containing the barcode
BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\barcode.jpg "));
// Scan the barcode from the loaded image
String result = BarcodeScanner.scanOne(bufferedImage);
// Output the scanned barcode result
System.out.print(result);
}
}
Explanation
- ImageIO.read() loads the image file, supporting extensions such as .png, .jpeg, .bmp, or .gif.
- BarcodeScanner.scanOne() detects and decodes the barcode from the image.
- The decoded result is stored in a String .
Note
The scanOne() method and the scan() method, which will be discussed later, can accept not only a BufferedImage as a parameter but also an InputStream and a String representing the image file path. Whether you're processing images from disk, user uploads, or real-time streams, this flexibility simplifies integration into diverse workflows.
Output:

Reading Multiple Barcodes from One Image
Spire.Barcode can detect and decode multiple barcodes in a single image. Here’s how:
import com.spire.barcode.BarcodeScanner;
import com.spire.barcode.license.LicenseProvider;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class ReadMultipleBarcodes {
public static void main(String[] args) throws IOException {
// Apply license key to remove restrictions on barcode types
LicenseProvider.setLicenseKey("your license key");
// Load the image file containing the barcode
BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\barcodes.jpg"));
// Scan the barcode from the loaded image
String[] results = BarcodeScanner.scan(bufferedImage);
// Output the results
System.out.println(Arrays.toString(results));
}
}
Explanation
- BarcodeScanner.scan() identifies and decodes all the barcodes present in the image.
- The results are stored in a String array .
Output:

Customizing Barcode Recognition Settings
For improved accuracy, Spire.Barcode allows you to customize scan settings, such as defining a scan region or specifying a particular barcode type. This enhanced approach ensures you have the flexibility and control needed for effective barcode scanning in Java.
Here is an example:
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeScanner;
import com.spire.barcode.license.LicenseProvider;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class CustomScanSettings {
public static void main(String[] args) throws IOException {
// Apply license key to remove restrictions on barcode types
LicenseProvider.setLicenseKey("your license key");
// Load the image file containing the barcode
BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\barcodes.jpg"));
// Define a rectangle area for barcode recognition
Rectangle rectangle = new Rectangle(0,0,380,270);
// Scan the barcode from the loaded image
String[] results = BarcodeScanner.scan(bufferedImage, rectangle, BarCodeType.Code_93);
// Output the first result
System.out.print(results[0]);
}
}
Explanation
- Rectangle() defines a specific area within the image for barcode recognition.
- BarCodeType enumeration allows you to specify the barcode type for more accurate detection.
Output:

Conclusion
In this article, we've explored the essential steps to set up Spire.Barcode in your Java project, read barcodes from images , handle multiple barcodes , and customize recognition settings for optimal accuracy. By leveraging these capabilities, developers can seamlessly integrate barcode scanning into their applications, improving data entry automation and reducing errors.
With Spire.Barcode, you have a reliable tool at your disposal to meet your barcode reading needs, paving the way for more efficient business operations.
FAQs
Q1. What types of barcodes can Spire.Barcode read?
Spire.Barcode supports 38+ barcode types, including both 1D barcodes like Code 128, Code 39, EAN-13, and UPC-A, as well as 2D barcodes such as QR Code, DataMatrix, and PDF417.
Q2. Can I customize the barcode scanning region?
Yes, Spire.Barcode allows you to define a specific scan area within the image by using a Rectangle object. This feature helps improve accuracy by focusing on a designated section of the image.
Q3. Can Spire.Barcode read multiple barcodes from a single image?
Yes! Using BarcodeScanner.scan(), you can detect and decode multiple barcodes in one image efficiently.
Q4. Is a license required to use Spire.Barcode for barcode recognition?
A commercial license is needed for full functionality, but you can get a free 30-day trial license to test all features before purchasing.
Q5. Can I use Spire.Barcode for Java to create barcodes?
Yes, Spire.Barcode supports generating over 38 commonly used 1D and 2D barcodes. For more information, check out: How to Create Barcode in Java
How to Read Excel Files in Java (XLS/XLSX) – Complete Guide
2025-06-13 08:30:27 Written by Administrator
Reading Excel files using Java is a common requirement in enterprise applications, especially when dealing with reports, financial data, user records, or third-party integrations. Whether you're building a data import feature, performing spreadsheet analysis, or integrating Excel parsing into a web application, learning how to read Excel files in Java efficiently is essential.
In this tutorial, you’ll discover how to read .xls and .xlsx Excel files using Java. We’ll use practical Java code examples which also cover how to handle large files, read Excel files from InputStream, and extract specific content line by line.
Table of Contents
- 1. Set Up Your Java Project
- 2. How to Read XLSX and XLS Files in Java
- 3. Best Practices for Large Excel Files
- 4. Full Example: Java Program to Read Excel File
- 5. Summary
- 6. FAQ
1. Set Up Your Java Project
To read Excel files using Java, you need a library that supports spreadsheet file formats. Spire.XLS for Java offers support for both .xls (legacy) and .xlsx (modern XML-based) files and provides a high-level API that makes Excel file reading straightforward.
Add Spire.XLS to Your Project
If you're using Maven, add the following to 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.xls</artifactId>
<version>16.6.5</version>
</dependency>
</dependencies>
If you're not using Maven, you can manually download the JAR from the official Spire.XLS website and add it to your classpath.
For smaller Excel processing tasks, you can also choose Free Spire.XLS for Java.
2. How to Read XLSX and XLS Files in Java
Java programs can easily read Excel files by loading the workbook and iterating through worksheets, rows, and cells. The .xlsx format is commonly used in modern Excel, while .xls is its older binary counterpart. Fortunately, Spire.XLS supports both formats seamlessly with the same code.
Load and Read Excel File (XLSX or XLS)
Here’s a basic example that loads an Excel file and prints its content:
import com.spire.xls.*;
public class ReadExcel {
public static void main(String[] args) {
// Create a workbook object and load the Excel file
Workbook workbook = new Workbook();
workbook.loadFromFile("data.xlsx"); // or "data.xls"
// Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Loop through each used row and column
for (int i = 1; i <= sheet.getLastRow(); i++) {
for (int j = 1; j <= sheet.getLastColumn(); j++) {
// Get cell text of a cell range
String cellText = sheet.getCellRange(i, j).getValue();
System.out.print(cellText + "\t");
}
System.out.println();
}
}
}
You can replace the file path with an .xls file and the code remains unchanged. This makes it simple to read Excel files using Java regardless of format.
The Excel file being read and the output result shown in the console.

Read Excel File Line by Line with Row Objects
In scenarios like user input validation or applying business rules, processing each row as a data record is often more intuitive. In such cases, you can read the Excel file line by line using row objects via the getRows() method.
for (int i = 0; i < sheet.getRows().length; i++) {
// Get a row
CellRange row = sheet.getRows()[i];
if (row != null && !row.isBlank()) {
for (int j = 0; j < row.getColumns().length; j++) {
String text = row.getColumns()[j].getText();
System.out.print((text != null ? text : "") + "\t");
}
System.out.println();
}
}
This technique works particularly well when reading Excel files in Java for batch operations or when you only need to process rows individually.
Read Excel File from InputStream
In web applications or cloud services, Excel files are often received as streams. Here’s how to read Excel files from an InputStream in Java:
import com.spire.xls.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class ReadExcel {
public static void main(String[] args) throws FileNotFoundException {
// Create a InputStream
InputStream stream = new FileInputStream("data.xlsx");
// Load the Excel file from the stream
Workbook workbook = new Workbook();
workbook.loadFromStream(stream);
System.out.println("Load Excel file successfully.");
}
}
This is useful when handling file uploads, email attachments, or reading Excel files stored in remote storage.
Read Excel Cell Values in Different Formats
Once you load an Excel file and get access to individual cells, Spire.XLS allows you to read the contents in various formats—formatted text, raw values, formulas, and more.
Here's a breakdown of what each method does:
CellRange cell = sheet.getRange().get(2, 1); // B2
// Formatted text (what user sees in Excel)
String text = cell.getText();
// Raw string value
String value = cell.getValue();
// Generic object (number, boolean, date, etc.)
Object rawValue = cell.getValue2();
// Formula (if exists)
String formula = cell.getFormula();
// Evaluated result of the formula
String result = cell.getEnvalutedValue();
// If it's a number cell
double number = cell.getNumberValue();
// If it's a date cell
java.util.Date date = cell.getDateTimeValue();
// If it's a boolean cell
boolean bool = cell.getBooleanValue();
Tip: Use getValue2() for flexible handling, as it returns the actual underlying object. Use getText() when you want to match Excel's visible content.
You May Also Like: How to Write Data into Excel Files in Java
3. Best Practices for Reading Large Excel Files in Java
When your Excel file contains tens of thousands of rows or multiple sheets, performance can become a concern. To ensure your Java application reads large Excel files efficiently:
- Load only required sheets
- Access only relevant columns or rows
- Avoid storing entire worksheets in memory
- Use row-by-row reading patterns
Here’s an efficient pattern for reading only non-empty rows:
for (int i = 1; i <= sheet.getRows().length; i++) {
Row row = sheet.getRows()[i];
if (row != null && !row.isBlank()) {
// Process only rows with data
}
}
Even though Spire.XLS handles memory efficiently, following these practices helps scale your Java Excel reading logic smoothly.
See also: Delete Blank Rows and Columns in Excel Using Java
4. Full Example: Java Program to Read Excel File
Here’s a full working Java example that reads an Excel file (users.xlsx) with extended columns such as name, email, age, department, and status. The code extracts only the original three columns (name, email, and age) and filters the output for users aged 30 or older.
import com.spire.xls.*;
public class ExcelReader {
public static void main(String[] args) {
Workbook workbook = new Workbook();
workbook.loadFromFile("users.xlsx");
Worksheet sheet = workbook.getWorksheets().get(0);
System.out.println("Name\tEmail\tAge");
for (int i = 2; i <= sheet.getLastRow(); i++) {
String name = sheet.getCellRange(i, 1).getValue();
String email = sheet.getCellRange(i, 2).getValue();
String ageText = sheet.getCellRange(i, 3).getValue();
int age = 0;
try {
age = Integer.parseInt(ageText);
} catch (NumberFormatException e) {
continue; // Skip rows with invalid age data
}
if (age >= 30) {
System.out.println(name + "\t" + email + "\t" + age);
}
}
}
}
Result of Java program reading the Excel file and printing its contents. 
This code demonstrates how to read specific cells from an Excel file in Java and output meaningful tabular data, including applying filters on data such as age.
5. Summary
To summarize, this article showed you how to read Excel files in Java using Spire.XLS, including both .xls and .xlsx formats. You learned how to:
- Set up your Java project with Excel-reading capabilities
- Read Excel files using Java in row-by-row or stream-based fashion
- Handle legacy and modern Excel formats with the same API
- Apply best practices when working with large Excel files
Whether you're reading from an uploaded spreadsheet, a static report, or a stream-based file, the examples provided here will help you build robust Excel processing features in your Java applications.
If you want to unlock all limitations and experience the full power of Excel processing, you can apply for a free temporary license.
6. FAQ
Q1: How to read an Excel file dynamically in Java?
To read an Excel file dynamically in Java—especially when the number of rows or columns is unknown—you can use getLastRow() and getLastColumn() methods to determine the data range at runtime. This ensures that your program can adapt to various spreadsheet sizes without hardcoded limits.
Q2: How to extract data from Excel file in Java?
To extract data from Excel files in Java, load the workbook and iterate through the cells using nested loops. You can retrieve values with getCellRange(row, column).getValue(). Libraries like Spire.XLS simplify this process and support both .xls and .xlsx formats.
Q3: How to read a CSV Excel file in Java?
If your Excel data is saved as a CSV file, you can read it using Java’s BufferedReader or file streams. Alternatively, Spire.XLS supports CSV parsing directly—you can load a CSV file by specifying the separator, such as Workbook.loadFromFile("data.csv", ","). This lets you handle CSV files along with Excel formats using the same API.
Q4: How to read Excel file in Java using InputStream?
Reading Excel files from InputStream in Java is useful in server-side applications, such as handling file uploads. With Spire.XLS, simply call workbook.loadFromStream(inputStream) and process it as you would with any file-based Excel workbook.