Converting Excel files to text files has several benefits. For example, it reduces file size, making data easier to store and share. In addition, text files are usually simple in structure, and converting Excel to text can make the document more straightforward for certain tasks. This article will demonstrate how to programmatically convert Excel to TXT format using Spire.XLS for Java.
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>14.11.0</version> </dependency> </dependencies>
Create Excel to TXT in Java
Spire.XLS for Java offers the Worksheet.saveToFile(String fileName, String separator, java.nio.charset.Charset encoding) method to convert a specified worksheet to a txt file. The following are the detailed steps.
- Create a Workbook instance.
- Load a sample Excel file using Workbook.loadFromFile() method.
- Get a specified worksheet by its index using Workbook.getWorksheets().get() method.
- Convert the Excel worksheet to a TXT file using Worksheet.saveToFile() method.
- Java
import com.spire.xls.*; import java.nio.charset.Charset; public class toText { public static void main(String[] args) { //Create a Workbook object Workbook workbook = new Workbook(); //Load a sample Excel file workbook.loadFromFile("sample.xlsx"); //Get the first worksheet Worksheet worksheet = workbook.getWorksheets().get(0); //Save the worksheet as a txt file Charset charset = Charset.forName("utf8"); worksheet.saveToFile("ExceltoTxt.txt", " ", charset); } }
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.