Of course! Converting an Excel file (.xlsx or .xls) to a text file (.txt) is a common task in Java. The most popular and robust library for this is Apache POI.

Here’s a complete guide, starting with the simplest approach and moving to more advanced options.
Prerequisites: Add Apache POI Dependency
You need to add the Apache POI library to your project. If you're using a build tool like Maven or Gradle, add the following dependencies.
For Maven (pom.xml)
<dependencies>
<!-- For .xlsx files (Office 2007 and later) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version> <!-- Use the latest version -->
</dependency>
<!-- For .xls files (Office 97-2003) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.5</version> <!-- Use the latest version -->
</dependency>
</dependencies>
For Gradle (build.gradle)
dependencies {
// For .xlsx files (Office 2007 and later)
implementation 'org.apache.poi:poi-ooxml:5.2.5' // Use the latest version
// For .xls files (Office 97-2003)
implementation 'org.apache.poi:poi:5.2.5' // Use the latest version
}
Method 1: Simple Conversion (All Data in One File)
This method reads all sheets and all cells and writes their content into a single text file, separating values with a tab (\t) and rows with a newline (\n).
The Code (SimpleConverter.java)
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
public class SimpleConverter {
public static void main(String[] args) {
// --- Configuration ---
String excelFilePath = "input.xlsx"; // Path to your Excel file
String txtFilePath = "output.txt"; // Path for the output text file
String delimiter = "\t"; // Use tab as the delimiter
// --- Main Logic ---
try (FileInputStream excelFile = new FileInputStream(excelFilePath);
Workbook workbook = WorkbookFactory.create(excelFile);
FileWriter txtWriter = new FileWriter(txtFilePath)) {
// Iterate over each sheet in the workbook
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
Sheet sheet = workbook.getSheetAt(i);
System.out.println("Processing sheet: " + sheet.getSheetName());
// Iterate over each row in the sheet
for (Row row : sheet) {
StringBuilder rowBuilder = new StringBuilder();
// Iterate over each cell in the row
for (Cell cell : row) {
// Get the cell value and convert it to a string
String cellValue = getCellValueAsString(cell);
rowBuilder.append(cellValue).append(delimiter);
}
// Write the row to the text file and remove the last trailing delimiter
txtWriter.write(rowBuilder.toString().trim());
txtWriter.write(System.lineSeparator()); // Use system-independent newline
}
}
System.out.println("Conversion complete! Text file saved to: " + txtFilePath);
} catch (IOException e) {
System.err.println("Error during conversion: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Helper method to get the cell value as a String, handling different cell types.
*/
private static String getCellValueAsString(Cell cell) {
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue();
case NUMERIC:
// Check if it's a date or a regular number
if (DateUtil.isCellDateFormatted(cell)) {
return cell.getDateCellValue().toString();
} else {
// Format number to avoid scientific notation (e.g., 1.0E7)
return DataFormatter.formatCellValue(cell);
}
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
case FORMULA:
// Evaluate the formula and get the resulting value
return DataFormatter.formatCellValue(cell);
case BLANK:
return "";
default:
return "";
}
}
}
How to Run:
- Save the code as
SimpleConverter.java. - Place your Excel file (e.g.,
input.xlsx) in the same directory. - Compile and run the code from your terminal:
javac -cp ".:$(echo $(find ~/.m2/repository -path '*/poi/*' -name '*.jar' | tr '\n' ':'))" SimpleConverter.java java -cp ".:$(echo $(find ~/.m2/repository -path '*/poi/*' -name '*.jar' | tr '\n' ':'))" SimpleConverter
Note: The classpath setup can be complex. Using an IDE like IntelliJ or Eclipse will handle this automatically.
(图片来源网络,侵删)
Method 2: Advanced Conversion (One Text File Per Sheet)
This is more useful if you want to keep the data from each sheet separate. It will create output_sheet1.txt, output_sheet2.txt, etc.
The Code (AdvancedConverter.java)
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
public class AdvancedConverter {
public static void main(String[] args) {
String excelFilePath = "input.xlsx";
String outputDir = "output_txt_files"; // Directory for the output files
String delimiter = ","; // Use comma as the delimiter this time
try (FileInputStream excelFile = new FileInputStream(excelFilePath);
Workbook workbook = WorkbookFactory.create(excelFile)) {
// Create the output directory if it doesn't exist
java.io.File dir = new java.io.File(outputDir);
if (!dir.exists()) {
dir.mkdirs();
}
// Iterate over each sheet
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
Sheet sheet = workbook.getSheetAt(i);
String sheetName = sheet.getSheetName();
// Sanitize sheet name to be a valid file name
String safeSheetName = sheetName.replaceAll("[^a-zA-Z0-9.-]", "_");
String txtFilePath = outputDir + java.io.File.separator + safeSheetName + ".txt";
try (FileWriter txtWriter = new FileWriter(txtFilePath)) {
System.out.println("Processing sheet: " + sheetName + " -> " + txtFilePath);
// Iterate over each row
for (Row row : sheet) {
StringBuilder rowBuilder = new StringBuilder();
// Iterate over each cell
for (Cell cell : row) {
rowBuilder.append(getCellValueAsString(cell)).append(delimiter);
}
txtWriter.write(rowBuilder.toString().trim());
txtWriter.write(System.lineSeparator());
}
}
}
System.out.println("All sheets converted successfully!");
} catch (IOException e) {
System.err.println("Error during conversion: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Helper method to get the cell value as a String (same as before).
*/
private static String getCellValueAsString(Cell cell) {
if (cell == null) {
return "";
}
DataFormatter dataFormatter = new DataFormatter();
return dataFormatter.formatCellValue(cell);
}
}
Key Differences:
- Output Directory: It creates a directory named
output_txt_files. - File Naming: For each sheet, it creates a new file (e.g.,
Sheet1.txt,Sheet2.txt). It also sanitizes the sheet name to avoid invalid characters in filenames. - Delimiter: I've changed the delimiter to a comma () to show it's configurable.
Method 3: CSV Conversion (Best for Importing into Other Programs)
A Comma-Separated Values (CSV) file is a special type of text file that is almost universally supported by databases, data analysis tools (like pandas, R), and other spreadsheet applications. The "Advanced Converter" is already very close to creating a CSV.
To make it a true CSV, you need to handle two things:
- Enclose fields in double quotes if they contain the delimiter, a newline, or a double quote.
- Escape double quotes within a field by doubling them ( becomes ).
Here is the robust CSV conversion logic.

The Code (CsvConverter.java)
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
public class CsvConverter {
public static void main(String[] args) {
String excelFilePath = "input.xlsx";
String csvFilePath = "data.csv";
try (FileInputStream excelFile = new FileInputStream(excelFilePath);
Workbook workbook = WorkbookFactory.create(excelFile);
FileWriter csvWriter = new FileWriter(csvFilePath)) {
Sheet sheet = workbook.getSheetAt(0); // Process only the first sheet for simplicity
System.out.println("Processing sheet: " + sheet.getSheetName() + " into " + csvFilePath);
for (Row row : sheet) {
for (int i = 0; i < row.getLastCellNum(); i++) {
Cell cell = row.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
String value = getCellValueAsString(cell);
// 1. Enclose in quotes if value contains comma, newline, or quote
if (value.contains(",") || value.contains("\n") || value.contains("\"")) {
value = value.replace("\"", "\"\""); // 2. Escape quotes
value = "\"" + value + "\"";
}
csvWriter.append(value);
if (i < row.getLastCellNum() - 1) {
csvWriter.append(",");
}
}
csvWriter.append(System.lineSeparator());
}
System.out.println("CSV conversion complete!");
} catch (IOException e) {
System.err.println("Error during conversion: " + e.getMessage());
e.printStackTrace();
}
}
private static String getCellValueAsString(Cell cell) {
if (cell == null) {
return "";
}
DataFormatter dataFormatter = new DataFormatter();
return dataFormatter.formatCellValue(cell);
}
}
This CSV version is the most recommended approach for data portability. You can easily adapt the "Advanced Converter" to use this logic to create one CSV file per sheet.
