110,499
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
///将Word文档转换成Html文件
/// </summary>
/// <param name="docpath"> Word文件所在完整路径</param>
/// <param name="savepath">生成后Html保存路径</param>
public static void ConvertWordToHtml(string docpath, string savepath)
{
try
{
// 1、指定原文件和目标文件
object Source = docpath;
string SaveHtmlPath = savepath + "\\index.html";
object Target = SaveHtmlPath;
// 2、缺省参数 //为了保险,只读方式打开
object Unknown = Type.Missing;
object readOnly = true;
object visible = false;
// 3、打开doc文件
Microsoft.Office.Interop.Word.Application newApp = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = newApp.Documents.Open(ref Source, ref Unknown,
ref readOnly, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref visible, ref Unknown, ref Unknown, ref Unknown, ref Unknown);
// 4、指定另存为格式(HTML)
Type docType = doc.GetType();
object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML;
doc.SaveAs(ref Target, ref format,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown);
// 5、关闭文档和Word程序
doc.Close(ref Unknown, ref Unknown, ref Unknown);
newApp.Quit(ref Unknown, ref Unknown, ref Unknown);
// 6、以下是利用文件流写入html,设置右键屏蔽和禁止复制的功能。
System.IO.StreamReader sr = new System.IO.StreamReader(SaveHtmlPath, Encoding.GetEncoding("GB2312"));
string html = sr.ReadToEnd();
sr.Close();
html = System.Text.RegularExpressions.Regex.Replace(html, @"<body[^>]*>", "<body oncontextmenu='return false' onselectstart='return false'>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.IO.StreamWriter sw = new System.IO.StreamWriter(SaveHtmlPath, false, Encoding.GetEncoding("GB2312"));
sw.Write(html);
sw.Close();
}
// 处理异常
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
}