需要补一下using和引用Microsoft.Office.Interop.Word这个dll(word的pia):
static void Main(string[] args)
{
string inputName = Console.ReadLine(); //打开文件的位置
string ext = Path.GetExtension(inputName);
string outputName =inputName.Replace(ext,".doc"); // 同路径保存
if(File.Exists(inputName))
{
objectoMissing = System.Reflection.Missing.Value;
objectoTrue = true;
objectoFalse = false;
Microsoft.Office.Interop.Word._Application oWord= new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word._Document oWordDoc= new Microsoft.Office.Interop.Word.Document();
oWord.Visible = false;
// 这里是打开文件的扩展名
objectopenFormat =Microsoft.Office.Interop.Word.WdOpenFormat.wdOpenFormatWebPages;
objectopenName = inputName;
oWordDoc =oWord.Documents.Open(ref openName, ref oMissing, ref oTrue, refoMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref openFormat, ref oMissing, ref oMissing, refoMissing, ref oMissing, ref oMissing, ref oMissing);
objectsaveFileName = outputName;
// 这里是保存文件的扩展名
objectsaveFormat =Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
oWordDoc.SaveAs(ref saveFileName, ref saveFormat,ref oMissing, ref oMissing, ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
oWordDoc.Close(ref oTrue, ref oMissing, refoMissing);
oWord.Quit(ref oTrue, ref oMissing, refoMissing);
}
}
这段代码实现了在命令行里输入一个htm的绝对路径,将其自动转换为doc,要求就是htm是文本格式的,不带图片什么乱七八糟的,表格没问题,依赖msoffice。
-----------------------------------------------------------------------------------------
附更加无耻的方法,完全不依赖 MS office! 你猜到了吗?
就是直接将htm格式的文本保存为以.doc为扩展名的文件!
原因很简单,现在兼容doc的软件,包括ms office都可以打开htm的文件,即识别html代码。