做项目时有用webBrowser控件显示word文件的需要,但是比较惭愧,没有找到很舒心的方法,于是转而把word文件转换成单文件网页文件.mht来显示。p.s.:webBrowser控件宽度设置成750px比较能还原word文档的显示效果。
using System;
using System.Reflection;
using System.Text;
using System.IO;
using System.Collections;
using Microsoft.Office.Interop.Word;
public class Word2mht
{
/// <summary>
/// 提取文件绝对路径的文件名部分,并把文件名后缀换成.mht
/// </summary>
/// <param name="Directory"></param>
/// <returns></returns>
static public string GetMhtName(string Directory)
{
int pathLength = Directory.LastIndexOf(Path.DirectorySeparatorChar);
string tmp = Directory.Substring(pathLength + 1);
int dot = tmp.LastIndexOf('.');
return DateTime.Today+tmp.Substring(0, dot)+".mht";
}
/// <summary>
/// word转成mht
/// </summary>
/// <param name="wordFileName"></param>
static public string WordToMht(string wordDirectory, string saveFileName)
{
Application word = new Application();
Type wordType = word.GetType();
Documents wordDocs = word.Documents;
//打开Word文件
Type docsType = wordDocs.GetType();
Document doc = (Document)docsType.InvokeMember(
"Open",
BindingFlags.InvokeMethod,
null,
wordDocs,
new Object[]
{
(object)(wordDirectory),
true,
true
}
);
//转换格式,另存为
Type docType = doc.GetType();
docType.InvokeMember(
"SaveAs",
BindingFlags.InvokeMethod,
null,
doc,
new object[]
{
(object)saveFileName,
WdSaveFormat.wdFormatWebArchive
}
);
docType.InvokeMember("Close", BindingFlags.InvokeMethod, null, doc, null);
//退出Word
wordType.InvokeMember("Quit", BindingFlags.InvokeMethod, null, word, null);
return saveFileName;
}
}
也看得出来吧,用了office的接口,没装office是没法用的。