1、在程序中先添加dll文件引用:
2、页面中引用命名空间:
using Word = Microsoft.Office.Interop.Word;
3、 上代码:
//开始统计word文件中的字数
object filePath = "/upload/123.docx"; //这里是Word文件的路径
filePath = Server.MapPath(filePath.ToString()); //word物理路径
//启动Word程序
object oMissing = Missing.Value;
object Nothing = Missing.Value;
Word.Application wordApp = new Word.ApplicationClass(); //Word应用程序变量
Word.Document wordDoc = wordApp.Documents.Open( //Word文档变量
ref filePath, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);
//字数(这个及其不准确,把空格也算进去)
int wordNum = wordDoc.Characters.Count;
Word.Range docRanger = wordDoc.Content;
//字数
int Words = docRanger.ComputeStatistics(Word.WdStatistic.wdStatisticWords);
//字符数(不计空格)
int Characters = docRanger.ComputeStatistics(Word.WdStatistic.wdStatisticCharacters);
//字符数(计空格)
int Characterswithspaces = docRanger.ComputeStatistics(Word.WdStatistic.wdStatisticCharactersWithSpaces);
//中文字符和朝鲜语单词
int Fareastcharacters = docRanger.ComputeStatistics(Word.WdStatistic.wdStatisticFarEastCharacters);
//段落数
int Paragraphs = docRanger.ComputeStatistics(Word.WdStatistic.wdStatisticParagraphs);
//行数
int Lines = docRanger.ComputeStatistics(Word.WdStatistic.wdStatisticLines);
//页数
int Pages = docRanger.ComputeStatistics(Word.WdStatistic.wdStatisticPages);
//输出
//关闭文件
wordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
//退出Word程序
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
4、上效果:
这是Word(123.docx)点击【审阅】-【字数统计】查看字数、字符数等。
这是在前台页面中输出,方便查看。
48 就那个及其 不准确统计,把空格也算进去 ;
10 、16、35、5 分别是 字数、字符数(不计空格)、字符数(计空格)、中文字符