很多人用java進行文檔操作時經常會碰到一個問題,就是如何獲得Word,Excel,pdf等文檔的內容?我研究了一下,在這里總結一下抽取word,pdf的幾種方法。 Title: word extraction Description: email:chris@matrix.org.cn Copyright: Matrix Copyright (c) 2003 Company: Matrix.org.cn
1. 用jacob
其實jacob是一個bridage,連接java和com或者win32函數的一個中間件,jacob并不能直接抽取word,excel等文件,需要自己寫dll哦,不過已經有為你寫好的了,就是jacob的作者一并提供了。
jacob jar與dll文件下載: http://danadler.com/jacob/
下載了jacob并放到指定的路徑之后(dll放到path,jar文件放到classpath),就可以寫你自己的抽取程序了,下面是一個簡單的例子: import java.io.File;
2. 用apache的poi來抽取word,excel。
import com.jacob.com.*;
import com.jacob.activeX.*;
/**
* Title: pdf extraction
* Description: email:chris@matrix.org.cn
* Copyright: Matrix Copyright (c) 2003
* Company: Matrix.org.cn
* @author chris
* @version 1.0,who use this example pls remain the declare
*/
public class FileExtracter{
public static void main(String[] args) {
ActiveXComponent component = new ActiveXComponent("Word.application");
String inFile = "c://test.doc";
String tpFile = "c://temp.htm";
String otFile = "c://temp.xml";
boolean flag = false;
try {
component.setObject wordacc = component.getProperty("document.").toDispatch();
Object wordfile = Dispatch.invoke(wordacc,"Open", Dispatch.Method,
new Object[]{inFile,new Variant(false), new Variant(true)},
new int[1] ).toDispatch();
Dispatch.invoke(wordfile,"SaveAs", Dispatch.Method, new Object[]{tpFile,new Variant(8)}, new int[1]);
Variant f = new Variant(false);
Dispatch.call(wordfile, "Close", f);
flag = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
component.invoke("Quit", new Variant[] {});
}
}
}
poi是apache的一個項目,不過就算用poi你可能都覺得很煩,不過不要緊,這里提供了更加簡單的一個接口給你:
下載經過封裝后的poi包: http://jakarta.apache.org/poi/
下載之后,放到你的classpath就可以了,下面是如何使用它的一個例子: import java.io.*;
3. pdfbox-用來抽取pdf文件
import org.textmining.text.extraction.WordExtractor;
/**
*
*
*
*
* @author chris
* @version 1.0,who use this example pls remain the declare
*/
public class PdfExtractor {
public PdfExtractor() {
}
public static void main(String args[]) throws Exception
{
FileInputStream in = new FileInputStream ("c://a.doc");
WordExtractor extractor = new WordExtractor();
String str = extractor.extractText(in);
System.out.println("the result length is"+str.length());
System.out.println("the result is"+str);
}
}
但是pdfbox對中文支持還不好,先下載pdfbox: http://www.pdfbox.org/
下面是一個如何使用pdfbox抽取pdf文件的例子: import org.pdfbox.pdmodel.PDdocument.
import org.pdfbox.pdfparser.PDFParser;
import java.io.*;
import org.pdfbox.util.PDFTextStripper;
import java.util.Date;
/**
*
新聞熱點
疑難解答