我正在尝试使用 JavaScript 计算 Microsoft Word 文档中的字数 我设法计算普通文本文件中的单词数。有没有办法使用“JavaScript API for Office”或任何其他方法对 Microsoft Word 文件执行此操作。
检查这个小东西 https://plnkr.co/edit/5TJfNiPxv275GuimdIlj?p=preview
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<h2>Microsoft Word Document Count Words! Using JavaScript?</h2>
<input type="file" accept=".doc,.txt,.docx" onchange="calculateWords()" id="textDoc"/>
<div>
<h1 id="fileInformation">File word Count after choose</h1>
</div>
</body>
</html>
JavaScript 代码
function calculateWords() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
console.log("words");
var doc = document.getElementById("textDoc");
var f = doc.files[0];
if (!f) {
alert("Failed to load file");
//validate file types yet to come
} else if (false) {
alert(f.type + " is not a valid text file.");
} else {
var r = new FileReader();//create file reader object
r.readAsText(f);//read file as text
//attach function to execute when loading file finishes.
r.onload = function (e) {
var contents = e.target.result;
var res = contents.split(" ");
console.log(res.length);
var fileInformation = "word Count = "+res.length;
var info = document.getElementById("fileInformation");
info.innerHTML = fileInformation;
}
}
} else {
alert('The File APIs are not fully supported by your browser.');
}
}
最佳答案
Microsoft 文档与普通文本文件不同..它们是二进制文件。
因此,您必须将它们解码为纯文本,删除所有格式,删除页眉和页脚并继续。这是一个意义重大的挑战。
作为一个简单的例子,这是 RTF 文件的一部分:
{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard
This is some {\b bold} text.\par
}
.DOC 文件要复杂得多,但是是二进制文件。 DOCX 文件有所不同。
所以,简单来说:不,你不能这样做。
关于javascript - 使用 JavaScript - 如何计算 Microsoft Word 文档中的字数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37622351/