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 paragraphs = xdoc.getParagraphs();
           
            int count = 0;
            int i = 1;
            for (XWPFParagraph xwpfParagraph:paragraphs) {
            	int linLength = 0;
            	String lineStr = "";
            	List 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();
	}
    

}

 

你可能感兴趣的:(java)