Extract Text from MS Office 2007 files (docx, pptx, xlsx) in Java
Following is the code to extract text from MS office 2007 files i.e. docx, pptx, xlsx
Before start, Please download below library
- dom4j-1.1.jar
- poi-3.7-20101029.jar
- geronimo-stax-api_1.0_spec-1.0.jar
- poi-ooxml-3.7-20101029.jar
- poi-ooxml-schemas-3.7-20101029.jar
- poi-scratchpad-3.7-20101029.jar
- xmlbeans-2.3.0.jar
import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;
import org.apache.poi.xslf.XSLFSlideShow;
import org.apache.poi.xslf.extractor.XSLFPowerPointExtractor;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class readMs2007Files {
public static void main(String[] arg) throws Exception {
System.out.print("Enter file name : ");
Scanner sr = new Scanner(System.in);
String fileName = sr.nextLine();
sr.close();
File file = new File(fileName);
if (!file.exists()) {
System.out.println("Sorry File does not Exists!");
}
else {
if (file.getName().endsWith(".docx") || file.getName().endsWith(".DOCX")) {
System.out.println(new XWPFWordExtractor(
new XWPFDocument(new FileInputStream(file))).getText());
}
else if (file.getName().endsWith(".pptx")|| file.getName().endsWith(".PPTX")) {
System.out.println(new XSLFPowerPointExtractor(
new XMLSlideShow(new XSLFSlideShow(fileName))).getText());
}
else if (file.getName().endsWith(".xlsx")|| file.getName().endsWith(".XLSX")) {
System.out.println(new XSSFExcelExtractor(
new XSSFWorkbook(new FileInputStream(file))).getText());
}
else {
System.out.println("Enter only MS Office 2007 files");
}
}
}
}
Related post:
- Auto sizing columns in Excel files created with Apache POI in Java
- Java code to convert xlsx & xls to csv
- Read / Write CSV file in Java using opencsv library
