JAVA統計word字數

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

public class CountDoc {

   
    public static void countLength() throws IOException {
        File file = new File("F:\\2.docx");
        try {
            FileInputStream fis = new FileInputStream(file);
            XWPFDocument xdoc = new XWPFDocument(fis);
            
            List<XWPFParagraph> paragraphs = xdoc.getParagraphs();
           
            int count = 0;
            int i = 1;
            for (XWPFParagraph xwpfParagraph:paragraphs) {
            	int linLength = 0;
            	String lineStr = "";
            	List<XWPFRun> xwpfRuns = xwpfParagraph.getRuns();
            	for (XWPFRun xwpfRun : xwpfRuns) {
            		linLength +=  xwpfRun.toString().trim().length();
            		lineStr += xwpfRun.toString();
					count += xwpfRun.toString().trim().length();
				}
            	System.out.println("第"+i+"行內容:'"+lineStr+"'      長度:"+linLength);
            	i++;
			}
            System.out.println("文章總行數:"+paragraphs.size() +" 行");
            System.out.println("文章總字數:"+count);
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) throws Exception {
    	CountDoc.countLength();
	}
    

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章