编辑12/13/13: 我们不想引用COM组件,因为如果客户没有安装完全相同的Office版本,它就无法工作。幸运的是,Microsoft已经使2013 word.interop.dll向后兼容了。现在我们不必担心这个限制。一旦引用了dll,我们可以执行以下操作:
/// <summary>Gets the content of the word document</summary>
/// <param name="filePath">The path to the word document file</param>
/// <returns>The content of the document</returns>
public string ExtractText(string filePath)
{
if (string.IsNullOrEmpty(filePath))
throw new ArgumentNullException("filePath", "Input file path not specified.");
if (!File.Exists(filePath))
throw new FileNotFoundException("Input file not found at specified path.", "filepath");
var resultText = string.Empty;
Application wordApp = null;
try
{
wordApp = new Application();
var doc = wordApp.Documents.Open(filePath, Type.Missing, true);
if (doc != null)
{
if (doc.Content != null && !string.IsNullOrEmpty(doc.Content.Text))
resultText = doc.Content.Text.Normalize();
doc.Close();
}
}
finally
{
if (wordApp != null)
wordApp.Quit(false, Type.Missing, false);
}
return resultText;
}
.DOC
格式,这与.DOCX
格式非常不同。 - Mike Christensen