需要補(bǔ)一下using和引用Microsoft.Office.Interop.Word這個(gè)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;
// 這里是打開文件的擴(kuò)展名
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;
// 這里是保存文件的擴(kuò)展名
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);
}
}
這段代碼實(shí)現(xiàn)了在命令行里輸入一個(gè)htm的絕對(duì)路徑,將其自動(dòng)轉(zhuǎn)換為doc,要求就是htm是文本格式的,不帶圖片什么亂七八糟的,表格沒問題,依賴msoffice。
-----------------------------------------------------------------------------------------
附更加無(wú)恥的方法,完全不依賴 MS office! 你猜到了嗎?
就是直接將htm格式的文本保存為以.doc為擴(kuò)展名的文件!
原因很簡(jiǎn)單,現(xiàn)在兼容doc的軟件,包括ms office都可以打開htm的文件,即識(shí)別html代碼。