Word 字符数精确统计工具

复制代码
自动 fallback 全量扫描(100%准确)
java 复制代码
import org.apache.poi.ooxml.POIXMLProperties;
import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

/**
 * Word 字符统计工具
 *
 * 功能:
 * 自动 fallback 全量扫描(100%准确)
 *
 * 适用:
 * 上传限制 / 翻译计费 / 文档校验
 */
public class WordCharCounter {

    /**
     * 根据文件路径统计
     */
    public static int count(String path) throws Exception {
        try (InputStream is = new FileInputStream(path)) {
            return count(is);
        }
    }

    /**
     * 根据流统计
     */
    public static int count(InputStream is) throws Exception {

        try (XWPFDocument doc = new XWPFDocument(is)) {

//            // ========= ① 极速模式(读取 metadata) =========
//            int fast = readFastCount(doc);
//
//            if (fast > 0) {
//                return fast;
//            }

            // ========= ② fallback 全量扫描 =========
            return slowCount(doc);
        }
    }

    /**
     * 读取 Office/WPS 预计算字数(极快)
     */
    private static int readFastCount(XWPFDocument doc) {
        try {
            POIXMLProperties.ExtendedProperties props =
                    doc.getProperties().getExtendedProperties();

            return props.getUnderlyingProperties().getCharacters();
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 全量扫描统计(绝对准确)
     */
    private static int slowCount(XWPFDocument doc) {

        int total = 0;

        // 正文
        total += countElements(doc.getBodyElements());

        // header
        for (XWPFHeader header : doc.getHeaderList()) {
            total += countElements(header.getBodyElements());
        }

        // footer
        for (XWPFFooter footer : doc.getFooterList()) {
            total += countElements(footer.getBodyElements());
        }

        return total;
    }

    /**
     * 统计 bodyElements(段落 + 表格)
     */
    private static int countElements(List<IBodyElement> elements) {

        int total = 0;

        for (IBodyElement element : elements) {

            // 段落
            if (element instanceof XWPFParagraph) {
                total += ((XWPFParagraph) element).getText().length();
            }

            // 表格
            else if (element instanceof XWPFTable) {
                XWPFTable table = (XWPFTable) element;

                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        total += cell.getText().length();
                    }
                }
            }
        }

        return total;
    }

    // ================= 测试入口 =================

    public static void main(String[] args) throws Exception {

        int count = WordCharCounter.count(
                "d:\\测试解读word内容.docx"
        );

        System.out.println("字符总数: " + count);
    }
}

相关推荐
2301_816997889 小时前
Word版本介绍与选择
c#·word·xhtml
2301_8169978812 小时前
Word界面完全解析
word·xhtml
海兰15 小时前
【接上篇】多格式文档支持扩展方案(PDF_Word_Excel)
pdf·word·excel
松叶似针15 小时前
Flutter三方库适配OpenHarmony【doc_text】— Word 文档解析插件功能全景与适配价值
flutter·word·harmonyos
reasonsummer15 小时前
【办公类-109-10】20260228圆牌被子牌(接送卡&被子卡&床卡&入园卡_word编辑单面_添加有效期)
python·word
道纪书生15 小时前
解决报错:很抱歉,powerpoint/word/excel遇到错误,使其无法正常工作......
word·powerpoint·excel
南部余额15 小时前
Apache POI 从入门到实战:Excel 与 Word操作攻略
java·word·excel·poi
qq_546937272 天前
Word _ WPS 通用公文排版助手,支持标题、正文一键规范,发文机关、函线、装订线、公章、页码等常用部件一键解决
word·wps
橙露2 天前
Python 办公自动化:批量处理 Excel/Word/PPT 实战教程
python·word·excel
lpfasd1233 天前
Tauri vs Electron:高质量Word/PDF导出效果深度对比
electron·pdf·word