提醒:使用poi3.7類庫,下載相關jar包,java工程build path添加jar包引用
package com.smi.wordpage.tool;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class WordPageGetter {
/**
* @param args
*/
public static int sumpage=0;
public static void main(String[] args) {
// TODO Auto-generated method stub
WordPageGetter wpg =new WordPageGetter();
List<String> lstFileNames=wpg.getListFiles("E://驗收文檔141219","docx",true);
XWPFDocument docx;
try {
for(int i=0;i<lstFileNames.size();i++){
docx = new XWPFDocument(POIXMLDocument.openPackage(lstFileNames.get(i)));
int pages = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();//總頁數
// int wordCount = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters();// 忽略空格的總字符數 另外還有getCharactersWithSpaces()方法獲取帶空格的總字數。
System.out.println (lstFileNames.get(i)+" pages=" + pages );
sumpage+=pages;
docx=null;
}
System.out.println ("目錄下文檔總頁數 = " + sumpage );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//獲取目錄(包括子目錄)下所有suffix類型文件的完整路徑 目錄,類型,是否查詢子目錄
public List<String> getListFiles(String path, String suffix, boolean isdepth) {
List<String> lstFileNames = new ArrayList<String>();
File file = new File(path);
return listFile(lstFileNames, file, suffix, isdepth);
}
private List<String> listFile(List<String> lstFileNames, File f, String suffix, boolean isdepth) {
// 若是目錄, 採用遞歸的方法遍歷子目錄
if (f.isDirectory()) {
File[] t = f.listFiles();
for (int i = 0; i < t.length; i++) {
if (isdepth || t[i].isFile()) {
listFile(lstFileNames, t[i], suffix, isdepth);
}
}
} else {
String filePath = f.getAbsolutePath();
if (!suffix.equals("")) {
int begIndex = filePath.lastIndexOf(".");
String tempsuffix = "";
if (begIndex != -1) {
tempsuffix = filePath.substring(begIndex + 1, filePath.length());
if (tempsuffix.equals(suffix)) {
lstFileNames.add(filePath);
}
}
} else {
lstFileNames.add(filePath);
}
//System.out.println(filePath);
}
return lstFileNames;
}
}