標籤:
完成office檔案操作可以協助apache.poi包(我用poi-3.10-FINAL),匯入對應的jar包(最好所有匯入)
以下的程式示範了一些操作word的過程,具體的函數功能能夠查看此包的官方API
import java.io.*;import org.apache.poi.POIXMLDocument;import org.apache.poi.hwpf.HWPFDocument;import org.apache.poi.hwpf.extractor.*;import org.apache.poi.hwpf.usermodel.Range;//xwpf專門加強處理Word2007 .docx 格式import org.apache.poi.xwpf.usermodel.XWPFDocument;public class WordReader {WordExtractor wordExtractor;public static void main(String[] args) {System.out.println("該word文檔(docx格式)總頁數例如以下:");new WordReader().getPageCount("F:\\資料採礦及其應用論文格式.docx");System.out.println("\n擷取整個word常值內容:");System.out.println(new WordReader().getTextFromWord("F:\\word2003.doc"));System.out.println("按段擷取常值內容:");System.out.println(new WordReader().getTextByParagraph("F:\\word2003.doc"));}// 統計word檔案總頁數(僅docx格式的有效!) doc格式也有對應的方法,可是因為doc本身的問題,導致擷取的頁數總是錯誤的。public void getPageCount(String filePath) {XWPFDocument docx;try {docx = new XWPFDocument(POIXMLDocument.openPackage(filePath));int pages = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();// 總頁數int wordCount = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters();// 忽略空格的總字元數// 另外還有getCharactersWithSpaces()方法擷取帶空格的總字數。System.out.println("Total pages=" + pages +"頁; "+ " Total wordCount=" + wordCount);} catch (IOException e) {e.printStackTrace();}}// 擷取word文檔中全部文本的方法(僅對doc檔案有效)public String getTextFromWord(String filePath) {String res = null;File file = new File(filePath);try {FileInputStream fis = new FileInputStream(file);wordExtractor = new WordExtractor(fis);// 擷取全部文本res = wordExtractor.getText();fis.close();} catch (IOException e) {e.printStackTrace();}return res;}// 按段擷取文本(僅對doc檔案有效)public String getTextByParagraph(String filePath) {String res = null;FileInputStream fis;try {fis = new FileInputStream(filePath);wordExtractor = new WordExtractor(fis);// 擷取段文本String[] strArray = wordExtractor.getParagraphText();for (int i = 0; i < strArray.length; i++) {System.out.println("第 " + (i+1)+" 段\n"+strArray[i]);}// 這個建構函式從InputStream中載入Word文檔HWPFDocument doc = new HWPFDocument((InputStream) new FileInputStream(filePath));// 這個類為HWPF物件模型,對文檔範圍段操作Range range = doc.getRange();int num = range.numParagraphs();System.out.println("該文檔共" + num + "段");//空行也算一段System.out.println("擷取第"+num+"段內容例如以下:\n"+range.getParagraph(num-1).text());fis.close();} catch (IOException e) {e.printStackTrace();}return res;}}
著作權聲明:本文部落格原創文章,部落格,未經同意,不得轉載。
Java閱讀word程式說明檔案