1. 程式人生 > >C#html檔案轉word檔案

C#html檔案轉word檔案

public bool SaveAsWord(string htmlFilePath, string wordFilePath)
        {
            bool result = false;
            object missing = System.Reflection.Missing.Value;
            object readOnly = false;
            object isVisible = false;
            object htmlFile = htmlFilePath;
            object wordFile = wordFilePath;
            Microsoft.Office.Interop.Word.Application oWordApp = null;
            Microsoft.Office.Interop.Word.Document oWordDoc = null;
            try
            {
                object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
                oWordApp = new Microsoft.Office.Interop.Word.Application();
                oWordApp.Visible = false;
                oWordDoc = oWordApp.Documents.Open(ref   htmlFile, ref   isVisible, ref   readOnly, ref   missing,
                                                                                   ref   missing, ref   missing, ref   missing, ref   missing,
                                                                                   ref   missing, ref   format, ref   missing, ref   isVisible,
                                                                                   ref   missing, ref   missing, ref   missing, ref missing);
                oWordDoc.SaveAs(ref   wordFile, ref   format, ref   missing, ref   missing, ref   missing, ref   missing,
                                             ref   missing, ref   missing, ref   missing, ref   missing, ref   missing, ref   missing, ref   missing,
                                             ref   missing, ref   missing, ref   missing);

                result = true;
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(e.Message);
                result = false;
            }
            finally
            {
                if (oWordDoc != null)
                {
                    oWordDoc.Close(ref     missing, ref     missing, ref     missing);
                    oWordDoc = null;
                }
                if (oWordApp != null)
                {
                    oWordApp.Quit(ref   missing, ref   missing, ref   missing);
                    oWordApp = null;
                }
            }
            return result;
        }