Exemple #1
0
        /// <summary>
        /// Recupera el texto plano de un documento de word
        /// </summary>
        /// <returns></returns>
        private StringBuilder GetTextFromWord(object path)
        {
            StringBuilder text = new StringBuilder();

            Word.Application word = new Word.Application();

            object miss     = System.Reflection.Missing.Value;
            object readOnly = true;

            Word.Document docs = null;
            try
            {
                docs = word.Documents.Open(path, miss, readOnly, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss);

                for (int i = 0; i < docs.Paragraphs.Count; i++)
                {
                    text.Append(docs.Paragraphs[i + 1].Range.Text.ToString()).Append(" ");
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                if (docs != null)
                {
                    docs.Close(false);
                }
                word.Quit(false);
            }

            return(text);
        }
Exemple #2
0
        public Form1()
        {
            InitializeComponent();

            Word.Application application = new Word.Application();
            application.Visible       = true;
            application.DisplayAlerts = NetOffice.WordApi.Enums.WdAlertLevel.wdAlertsNone;
            Word.Document document = application.Documents.Add();
            application.Selection.TypeText("Hello World");

            int left   = 0;
            int top    = 0;
            int width  = 0;
            int height = 0;

            application.ActiveWindow.GetPoint(out left, out top, out width, out height, application.Selection.Range);

            MessageBox.Show(string.Format("GetPoint returns Left:{0} Top:{1} Width:{2} Height:{3}", left, top, width, height));

            try
            {
                application.Quit();
                application.Dispose();
            }
            catch
            {
                // may closed by user
            }
        }
Exemple #3
0
        public List <string> CreateReportWord()
        {
            string        appStatus;
            string        strRet  = null;
            List <string> appList = new List <string>();  //函数执行状态+文件名

            //测试使用的是fristpage

            using (m_wordApp = new Word.Application())
            {
                #region  定义类
                WriteFirstPage FirstPage = new OfficeDocGenerate.WriteFirstPage("ProjectNumber", "CompaneName");
                #endregion
                m_wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                m_utils = new Word.Tools.CommonUtils(m_wordApp);
                m_doc   = m_wordApp.Documents.Add();

                //SetPage();
                WriteFirstPage(model.ProjectNumber, model.CompaneName, model.ContractDate.Year + "年" + model.ContractDate.Month + "月" + model.ContractDate.Day + "日");

                //      m_doc.Paragraphs.Last.Range.InsertBreak();
                WriteInstruction();
                //         m_doc.Paragraphs.Last.Range.InsertBreak();
                appStatus = "0";
                //WriteTestReport(ParmeterChemicalModels, physicalmodels, chemicalmodels, str);
                strRet = SaveFile();
                appList.Add(appStatus);
                appList.Add(strRet);
            }
            return(appList);
        }
        public override void Fix(Word.Document doc, int hwnd, out MsoDocInspectorStatus status, out string result)
        {
            Word.Range range = doc.Content;
            Word.Find  find  = range.Find;

            int replacedLinks = 0;

            foreach (KeyValuePair <int, string> item in InspectResult)
            {
                string uri = TryGetBitlyRedirectUrl(item.Value);
                if (!String.IsNullOrWhiteSpace(uri))
                {
                    if (find.Execute(item.Value, null, null, null, null, null, null, null, null, uri))
                    {
                        replacedLinks++;
                    }
                }
            }

            if (replacedLinks == InspectResult.Count)
            {
                status = MsoDocInspectorStatus.msoDocInspectorStatusDocOk;
                result = "All links have been replaced.";
            }
            else
            {
                status = MsoDocInspectorStatus.msoDocInspectorStatusError;
                result = "Unable to replace one or more link(s).";
            }
        }
Exemple #5
0
 void IDocumentInspector.Inspect(object Doc, out MsoDocInspectorStatus Status, out string Result, out string Action)
 {
     Word.Document document = null;
     try
     {
         if (null != CurrentInspector)
         {
             document = COMObject.Create <Word.Document>(Factory, Doc);
             CurrentInspector.Inspect(document, out Status, out Result, out Action);
             return;
         }
         else
         {
             Status = MsoDocInspectorStatus.msoDocInspectorStatusError;
             Result = null;
             Action = null;
         }
     }
     catch
     {
         Status = MsoDocInspectorStatus.msoDocInspectorStatusError;
         Result = null;
         Action = null;
         throw;
     }
     finally
     {
         TryDisposeDocumentInspectorDocument(document, Doc);
     }
 }
        public List <string> CreateReportWord(List <string> strc, ProjectInfo projectmodels, List <TestChemicalReport> chemicalmodels)
        {
            string        appStatus;
            string        strRet  = null;
            List <string> appList = new List <string>();  //函数执行状态+文件名

            //测试使用的是fristpage

            using (m_wordApp = new Word.Application())
            {
                #region  定义类
                WriteFirstPage FirstPage = new OfficeDocGenerate.WriteFirstPage("2016SJ018", "北京京门世纪物业管理有限公司");
                #endregion
                m_wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                m_utils = new Word.Tools.CommonUtils(m_wordApp);
                m_doc   = m_wordApp.Documents.Add();

                //SetPage();
                WriteFirstPage(FirstPage.ReportNumber, FirstPage.Client, projectmodels.CreateTime.Year.ToString() + "年" + projectmodels.CreateTime.Month.ToString() + "月" + projectmodels.CreateTime.Day.ToString() + "日");
                m_doc.Paragraphs.Last.Range.InsertBreak();
                //         m_doc.Paragraphs.Last.Range.InsertBreak();
                WriteContent();
                m_doc.Paragraphs.Last.Range.InsertBreak();
                appStatus = WriteEmployerBasicInfo(projectmodels);
                WriteTestReport(chemicalmodels, strc);
                strRet = SaveFile();
                appList.Add(appStatus);
                appList.Add(strRet);
            }
            return(appList);
        }
Exemple #7
0
        public TestResult DoTest()
        {
            Word.Application application = null;
            DateTime         startTime   = DateTime.Now;

            try
            {
                application = new Word.Application();
                application.DisplayAlerts = WdAlertLevel.wdAlertsNone;

                Word.Document newDocument = application.Documents.Add();
                application.Selection.TypeText("This text is written by NetOffice");

                application.Selection.HomeKey(WdUnits.wdLine, WdMovementType.wdExtend);
                application.Selection.Font.Color = WdColor.wdColorSeaGreen;
                application.Selection.Font.Bold  = 1;
                application.Selection.Font.Size  = 18;

                newDocument.Close(false);

                return(new TestResult(true, DateTime.Now.Subtract(startTime), "", null, ""));
            }
            catch (Exception exception)
            {
                return(new TestResult(false, DateTime.Now.Subtract(startTime), exception.Message, exception, ""));
            }
            finally
            {
                if (null != application)
                {
                    application.Quit(WdSaveOptions.wdDoNotSaveChanges);
                    application.Dispose();
                }
            }
        }
 void Office.Native.IDocumentInspector.Fix(object Doc, Int32 Hwnd, out MsoDocInspectorStatus Status, out string Result)
 {
     try
     {
         Word.Document document = new Word.Document(Factory, null, Doc);
         try
         {
             Fix(document, Hwnd, out Status, out Result);
         }
         catch
         {
             Status = MsoDocInspectorStatus.msoDocInspectorStatusError;
             Result = null;
             throw;
         }
         finally
         {
             TryDisposeDocumentInspectorDocument(document);
         }
     }
     catch (Exception exception)
     {
         Status = MsoDocInspectorStatus.msoDocInspectorStatusError;
         Result = null;
         if (!OnBaseError(exception))
         {
             throw;
         }
     }
 }
Exemple #9
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="Doc"></param>
 /// <param name="Status"></param>
 /// <param name="Result"></param>
 /// <param name="Action"></param>
 void Office.Native.IDocumentInspector.Inspect(object Doc, out MsoDocInspectorStatus Status, out string Result, out string Action)
 {
     try
     {
         Word.Document document = COMObject.Create <Word.Document>(Factory, Doc);
         try
         {
             Inspect(document, out Status, out Result, out Action);
         }
         catch
         {
             Status = MsoDocInspectorStatus.msoDocInspectorStatusError;
             Result = null;
             Action = null;
             throw;
         }
         finally
         {
             TryDisposeDocumentInspectorDocument(document);
         }
     }
     catch (Exception exception)
     {
         Status = MsoDocInspectorStatus.msoDocInspectorStatusError;
         Result = null;
         Action = null;
         if (!OnBaseError(exception))
         {
             throw;
         }
     }
 }
Exemple #10
0
        public void RunExample()
        {
            // start word and turn off msg boxes
            Word.Application wordApplication = new Word.Application();
            wordApplication.DisplayAlerts = WdAlertLevel.wdAlertsNone;

            // create a utils instance, not need for but helpful to keep the lines of code low
            Word.Tools.CommonUtils utils = new Word.Tools.CommonUtils(wordApplication);

            // add a new document
            Word.Document newDocument = wordApplication.Documents.Add();

            // insert some text
            wordApplication.Selection.TypeText("This text is written by NetOffice");

            wordApplication.Selection.HomeKey(WdUnits.wdLine, WdMovementType.wdExtend);
            wordApplication.Selection.Font.Color = WdColor.wdColorSeaGreen;
            wordApplication.Selection.Font.Bold  = 1;
            wordApplication.Selection.Font.Size  = 18;

            // save the document
            string documentFile = utils.File.Combine(HostApplication.RootDirectory, "Example01", Word.Tools.DocumentFormat.Normal);

            newDocument.SaveAs(documentFile);

            // close word and dispose reference
            wordApplication.Quit();
            wordApplication.Dispose();

            // show dialog for the user(you!)
            HostApplication.ShowFinishDialog(null, documentFile);
        }
Exemple #11
0
        public static void Export(int id)
        {
            Word.Application wordApp = null;
            Word.Document    wordDoc = null;
            try
            {
                wordApp         = new Word.Application();
                wordApp.Visible = true;
                wordDoc         = wordApp.Documents.Open(Environment.CurrentDirectory + @"\Шаблон.docx");

                var document  = GetDocument(id);
                var firstDate = DateTime.ParseExact(document.FirstDate, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
                var lastDate  = DateTime.ParseExact(document.LastDate, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
                var nowDate   = DateTime.Now;
                wordDoc.Bookmarks["Номер_карточки"].Range.GetFormatingRange(document.Id.ToString());
                wordDoc.Bookmarks["Заявитель"].Range.GetFormatingRange($"{document.LName} {document.FName} {document.SName}");
                wordDoc.Bookmarks["Телефон"].Range.GetFormatingRange(document.Phone);
                wordDoc.Bookmarks["Улица"].Range.GetFormatingRange(document.Street);
                wordDoc.Bookmarks["Дом"].Range.GetFormatingRange(document.HomeNumber.ToString());
                wordDoc.Bookmarks["Квартира"].Range.GetFormatingRange(document.Apartment.ToString());
                wordDoc.Bookmarks["Содержание"].Range.GetFormatingRange(document.DescriptionProblem);
                wordDoc.Bookmarks["Работник"].Range.GetFormatingRange(document.Worker);
                wordDoc.Bookmarks["Дата_поступления"].Range.GetFormatingRange(firstDate.ToLongDateString());
                wordDoc.Bookmarks["Текущая_дата"].Range.GetFormatingRange(nowDate.ToLongDateString());
                wordDoc.Bookmarks["Дата_выполнения"].Range.GetFormatingRange(lastDate.ToLongDateString());
                wordDoc.Bookmarks["Результаты"].Range.GetFormatingRange(document.DescriptionResult);
                wordDoc.Bookmarks["Сумма"].Range.GetFormatingRange(document.Money.ToString());
            }
            finally
            {
                wordDoc?.Dispose();
                wordApp?.Quit();
            }
        }
Exemple #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public Document Fetch(string name)
        {
            //try to get the active PPT Instance
            this.application = Word.Application.GetActiveInstance();
            if (this.application == null)
            {
                //start PPT if ther is no active instance
                throw new Exception("Missing Word Application");
            }
            Word.Document document = null;
            if (name != null)
            {
                try
                {
                    document = new Word.Document(this.application.Documents[name]);
                }
                catch
                {
                    throw new Exception("Cannot find the word documents");
                }
            }
            else
            {
                document = new Word.Document(this.application.ActiveDocument);
            }

            return(new Document(document));
        }
Exemple #13
0
 void IDocumentInspector.Fix(object Doc, Int32 Hwnd, out MsoDocInspectorStatus Status, out string Result)
 {
     Word.Document document = null;
     try
     {
         if (null != CurrentInspector)
         {
             document = new Word.Document(Factory, null, Doc);
             CurrentInspector.Fix(document, Hwnd, out Status, out Result);
             return;
         }
         else
         {
             Status = MsoDocInspectorStatus.msoDocInspectorStatusError;
             Result = null;
         }
     }
     catch
     {
         Status = MsoDocInspectorStatus.msoDocInspectorStatusError;
         Result = null;
         throw;
     }
     finally
     {
         TryDisposeDocumentInspectorDocument(document, Doc);
     }
 }
Exemple #14
0
 private static async Task CheckSpellingTask(Word.Document doc)
 {
     try
     {
         doc.CheckSpelling();
     }
     catch { }
 }
Exemple #15
0
        // Utility Functions
        /// <summary>
        /// Extracts the text from a word document and returns it as a string.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private string extractWordDocument(string file)
        {
            NetOffice.WordApi.Application wordApplication = new NetOffice.WordApi.Application();
            NetOffice.WordApi.Document    newDocument     = wordApplication.Documents.Open(file);
            string txt = newDocument.Content.Text;

            wordApplication.Quit();
            wordApplication.Dispose();
            return(txt);
        }
        public void RunExample()
        {
            // start word and turn off msg boxes
            Word.Application wordApplication = new Word.Application();
            wordApplication.DisplayAlerts = WdAlertLevel.wdAlertsNone;

            // add a new document
            Word.Document newDocument = wordApplication.Documents.Add();

            // add a table
            Word.Table table = newDocument.Tables.Add(wordApplication.Selection.Range, 3, 2);

            // insert some text into the cells
            table.Cell(1, 1).Select();
            wordApplication.Selection.TypeText("This");

            table.Cell(1, 2).Select();
            wordApplication.Selection.TypeText("table");

            table.Cell(2, 1).Select();
            wordApplication.Selection.TypeText("was");

            table.Cell(2, 2).Select();
            wordApplication.Selection.TypeText("created");

            table.Cell(3, 1).Select();
            wordApplication.Selection.TypeText("by");

            table.Cell(3, 2).Select();
            wordApplication.Selection.TypeText("NetOffice");

            // we save the document as .doc for compatibility with all word versions
            string documentFile = string.Format("{0}\\Example02{1}", _hostApplication.RootDirectory, ".doc");
            double wordVersion  = Convert.ToDouble(wordApplication.Version, CultureInfo.InvariantCulture);

            if (wordVersion >= 12.0)
            {
                newDocument.SaveAs(documentFile, WdSaveFormat.wdFormatDocumentDefault);
            }
            else
            {
                newDocument.SaveAs(documentFile);
            }

            // close word and dispose reference
            wordApplication.Quit();
            wordApplication.Dispose();

            // show dialog for the user(you!)
            _hostApplication.ShowFinishDialog(null, documentFile);
        }
Exemple #17
0
        public TestResult DoTest()
        {
            Word.Application application = null;
            DateTime         startTime   = DateTime.Now;

            try
            {
                application = new Word.Application();
                application.DisplayAlerts = WdAlertLevel.wdAlertsNone;

                Word.Document newDocument = application.Documents.Add();
                Word.Table    table       = newDocument.Tables.Add(application.Selection.Range, 3, 2);

                // insert some text into the cells
                table.Cell(1, 1).Select();
                application.Selection.TypeText("This");

                table.Cell(1, 2).Select();
                application.Selection.TypeText("table");

                table.Cell(2, 1).Select();
                application.Selection.TypeText("was");

                table.Cell(2, 2).Select();
                application.Selection.TypeText("created");

                table.Cell(3, 1).Select();
                application.Selection.TypeText("by");

                table.Cell(3, 2).Select();
                application.Selection.TypeText("NetOffice");

                newDocument.Close(false);

                return(new TestResult(true, DateTime.Now.Subtract(startTime), "", null, ""));
            }
            catch (Exception exception)
            {
                return(new TestResult(false, DateTime.Now.Subtract(startTime), exception.Message, exception, ""));
            }
            finally
            {
                if (null != application)
                {
                    application.Quit(WdSaveOptions.wdDoNotSaveChanges);
                    application.Dispose();
                }
            }
        }
Exemple #18
0
        public void RunExample()
        {
            // start word and turn off msg boxes
            Word.Application wordApplication = new Word.Application();
            wordApplication.DisplayAlerts = WdAlertLevel.wdAlertsNone;
            wordApplication.Visible       = true;

            // create a utils instance, not need for but helpful to keep the lines of code low
            CommonUtils utils = new CommonUtils(wordApplication);

            // add a new document
            Word.Document newDocument = wordApplication.Documents.Add();

            // add new module and insert macro
            // the option "Trust access to Visual Basic Project" must be set
            VB.CodeModule module = newDocument.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule).CodeModule;

            // set the modulename
            module.Name = "NetOfficeTestModule";

            //add the macro
            string codeLines = string.Format("Public Sub NetOfficeTestMacro()\r\n   {0}\r\nEnd Sub",
                                             "Selection.TypeText (\"This text is written by a automatic created macro with NetOffice...\")");

            module.InsertLines(1, codeLines);

            //start the macro NetOfficeTestModule
            wordApplication.Run("NetOfficeTestModule!NetOfficeTestMacro");

            // save the document
            string documentFile = utils.File.Combine(HostApplication.RootDirectory, "Example05", DocumentFormat.Macros);

            newDocument.SaveAs(documentFile);
            if (utils.ApplicationIs2007OrHigher)
            {
                newDocument.SaveAs(documentFile, WdSaveFormat.wdFormatXMLDocumentMacroEnabled);
            }
            else
            {
                newDocument.SaveAs(documentFile);
            }

            //close word and dispose reference
            wordApplication.Quit();
            wordApplication.Dispose();

            // show end dialog
            HostApplication.ShowFinishDialog(null, documentFile);
        }
 /// <summary>
 /// Try dispose given document after Inspect/Fix
 /// </summary>
 /// <param name="document">given document as any</param>
 /// <returns>true if no error occured, otherwise false</returns>
 protected virtual bool TryDisposeDocumentInspectorDocument(Word.Document document)
 {
     try
     {
         if (null != document && false == document.IsDisposed)
         {
             document.Dispose();
         }
         return(true);
     }
     catch
     {
         return(false);
     }
 }
    protected void runWordApplication()
    {
        wordApplication = new Word.Application();
        wordApplication.DisplayAlerts = WdAlertLevel.wdAlertsNone;
        newDocument = wordApplication.Documents.Add();

        wordApplication.Selection.Font.Size = 11;
        wordApplication.Selection.Font.Name = "Corbel";

        firstTable();
        moveDownpar();
        secondTable();
        moveDownpar();
        thirdTable();
        moveDownpar();
        fouthTable();
        moveDownpar();
        fithTable();
        moveDownpar();

        wordApplication.Selection.TypeText(@"*Environments checked in this test run");
        wordApplication.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
        wordApplication.Selection.InlineShapes.AddPicture(imageLoc);
        wordApplication.Selection.MoveRight();
        wordApplication.ActiveWindow.Selection.TypeParagraph();
        wordApplication.Selection.PageSetup.HeaderDistance = 12.00f;
        wordApplication.Selection.PageSetup.FooterDistance = 12.00f;
        wordApplication.ActiveWindow.View.SeekView         = WdSeekView.wdSeekMainDocument;
        wordApplication.Selection.WholeStory();
        wordApplication.Selection.Font.Color = WdColor.wdColorBlack;

        string documentFile = newPath;

        double wordVersion = Convert.ToDouble(wordApplication.Version, CultureInfo.InvariantCulture);

        if (wordVersion >= 12.0)
        {
            newDocument.SaveAs(documentFile, WdSaveFormat.wdFormatDocumentDefault);
        }
        else
        {
            newDocument.SaveAs(documentFile);
        }

        // close word and dispose reference
        wordApplication.Quit();
        wordApplication.Dispose();
    }
Exemple #21
0
        public void RunExample()
        {
            // start word and turn off msg boxes
            Word.Application wordApplication = new Word.Application();
            wordApplication.DisplayAlerts = WdAlertLevel.wdAlertsNone;

            // create a utils instance, not need for but helpful to keep the lines of code low
            CommonUtils utils = new CommonUtils(wordApplication);

            // add a new document
            Word.Document newDocument = wordApplication.Documents.Add();

            // add a table
            Word.Table table = newDocument.Tables.Add(wordApplication.Selection.Range, 3, 2);

            // insert some text into the cells
            table.Cell(1, 1).Select();
            wordApplication.Selection.TypeText("This");

            table.Cell(1, 2).Select();
            wordApplication.Selection.TypeText("table");

            table.Cell(2, 1).Select();
            wordApplication.Selection.TypeText("was");

            table.Cell(2, 2).Select();
            wordApplication.Selection.TypeText("created");

            table.Cell(3, 1).Select();
            wordApplication.Selection.TypeText("by");

            table.Cell(3, 2).Select();
            wordApplication.Selection.TypeText("NetOffice");

            // save the document
            string documentFile = utils.File.Combine(HostApplication.RootDirectory, "Example02", Word.Tools.DocumentFormat.Normal);

            newDocument.SaveAs(documentFile);

            // close word and dispose reference
            wordApplication.Quit();
            wordApplication.Dispose();

            // show dialog for the user(you!)
            HostApplication.ShowFinishDialog(null, documentFile);
        }
Exemple #22
0
        public void RunExample()
        {
            // start word and turn off msg boxes
            Word.Application wordApplication = new Word.Application();
            wordApplication.DisplayAlerts = WdAlertLevel.wdAlertsNone;
            wordApplication.Visible       = true;

            // add a new document
            Word.Document newDocument = wordApplication.Documents.Add();

            // add new module and insert macro
            // the option "Trust access to Visual Basic Project" must be set
            VB.CodeModule module = newDocument.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule).CodeModule;

            // set the modulename
            module.Name = "NetOfficeTestModule";

            //add the macro
            string codeLines = string.Format("Public Sub NetOfficeTestMacro()\r\n   {0}\r\nEnd Sub",
                                             "Selection.TypeText (\"This text is written by a automatic created macro with NetOffice...\")");

            module.InsertLines(1, codeLines);

            //start the macro NetOfficeTestModule
            wordApplication.Run("NetOfficeTestModule!NetOfficeTestMacro");

            string fileExtension = GetFileExtension(wordApplication);
            string documentFile  = string.Format("{0}\\Example05{1}", _hostApplication.RootDirectory, fileExtension);
            double wordVersion   = Convert.ToDouble(wordApplication.Version, CultureInfo.InvariantCulture);

            if (wordVersion >= 12.0)
            {
                newDocument.SaveAs(documentFile, WdSaveFormat.wdFormatXMLDocumentMacroEnabled);
            }
            else
            {
                newDocument.SaveAs(documentFile);
            }

            //close word and dispose reference
            wordApplication.Quit();
            wordApplication.Dispose();

            // show dialog for the user(you!)
            _hostApplication.ShowFinishDialog(null, documentFile);
        }
Exemple #23
0
        public TestResult DoTest()
        {
            Word.Application application = null;
            DateTime         startTime   = DateTime.Now;

            try
            {
                application = COMObject.Create <Word.Application>(COMObjectCreateOptions.CreateNewCore);
                application.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                application.Visible       = true;

                Word.Document newDocument = application.Documents.Add();

                // add new module and insert macro
                // the option "Trust access to Visual Basic Project" must be set
                NetOffice.VBIDEApi.CodeModule module = newDocument.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule).CodeModule;

                // set the modulename
                module.Name = "NetOfficeTestModule";

                //add the macro
                string codeLines = string.Format("Public Sub NetOfficeTestMacro()\r\n   {0}\r\nEnd Sub",
                                                 "Selection.TypeText (\"This text is written by a automatic created macro with NetOffice...\")");
                module.InsertLines(1, codeLines);

                //start the macro NetOfficeTestModule
                application.Run("NetOfficeTestModule!NetOfficeTestMacro");

                newDocument.Close(false);

                return(new TestResult(true, DateTime.Now.Subtract(startTime), "", null, ""));
            }
            catch (Exception exception)
            {
                return(new TestResult(false, DateTime.Now.Subtract(startTime), exception.Message, exception, ""));
            }
            finally
            {
                if (null != application)
                {
                    application.Quit(WdSaveOptions.wdDoNotSaveChanges);
                    application.Dispose();
                }
            }
        }
Exemple #24
0
        private void buttonStartExample_Click(object sender, EventArgs e)
        {
            // start word and turn off msg boxes
            Word.Application wordApplication = new Word.Application();
            wordApplication.Visible = true;

            // we register some events. note: the event trigger was called from word, means an other Thread
            wordApplication.NewDocumentEvent         += new NetOffice.WordApi.Application_NewDocumentEventHandler(wordApplication_NewDocumentEvent);
            wordApplication.DocumentBeforeCloseEvent += new NetOffice.WordApi.Application_DocumentBeforeCloseEventHandler(wordApplication_DocumentBeforeCloseEvent);

            // add new document and close
            Word.Document document = wordApplication.Documents.Add();
            document.Close();

            // close word and dispose reference
            wordApplication.Quit();
            wordApplication.Dispose();
        }
Exemple #25
0
        public TestResult DoTest()
        {
            Word.Application application = null;
            DateTime         startTime   = DateTime.Now;

            try
            {
                application = new Word.Application();
                application.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                application.Visible       = true;

                Word.Document newDocument = application.Documents.Add();

                application.NewDocumentEvent         += new NetOffice.WordApi.Application_NewDocumentEventHandler(wordApplication_NewDocumentEvent);
                application.DocumentBeforeCloseEvent += new NetOffice.WordApi.Application_DocumentBeforeCloseEventHandler(wordApplication_DocumentBeforeCloseEvent);

                // add new document and close
                Word.Document document = application.Documents.Add();
                document.Close(false);

                if (_beforeCloseCalled && _newDocumentCalled)
                {
                    return(new TestResult(true, DateTime.Now.Subtract(startTime), "", null, ""));
                }
                else
                {
                    return(new TestResult(false, DateTime.Now.Subtract(startTime), string.Format("DocumentBeforeClose:{0}, NewDocument:{1}", _beforeCloseCalled, _newDocumentCalled), null, ""));
                }
            }
            catch (Exception exception)
            {
                return(new TestResult(false, DateTime.Now.Subtract(startTime), exception.Message, exception, ""));
            }
            finally
            {
                if (null != application)
                {
                    application.Quit(WdSaveOptions.wdDoNotSaveChanges);
                    application.Dispose();
                }
            }
        }
 private void listViewSearchResults_DoubleClick(object sender, EventArgs e)
 {
     try
     {
         if (listViewSearchResults.SelectedItems.Count > 0)
         {
             Word.Document activeDocument = Addin.Application.ActiveDocument;
             if (null != activeDocument)
             {
                 Customer selectedCustomer = listViewSearchResults.SelectedItems[0].Tag as Customer;
                 Addin.Application.Selection.TypeText(selectedCustomer.ToString());
                 activeDocument.Dispose();
             }
         }
     }
     catch (Exception exception)
     {
         MessageBox.Show(exception.Message, "An error is occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemple #27
0
        public List <string> CreateReportWord()
        {
            string        appStatus;
            string        strRet  = null;
            List <string> appList = new List <string>();  //函数执行状态+文件名

            //测试使用的是fristpage

            using (m_wordApp = new Word.Application())
            {
                m_wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                m_utils = new Word.Tools.CommonUtils(m_wordApp);
                m_doc   = m_wordApp.Documents.Add();
                WriteFirstPage();
                appStatus = "0";
                strRet    = SaveFile();
                appList.Add(appStatus);
                appList.Add(strRet);
            }
            return(appList);
        }
Exemple #28
0
        public Form1()
        {
            InitializeComponent();

            Word.Application application = new Word.Application();
            application.Visible = true;
            Word.Document document = application.Documents.Add();
            application.Selection.TypeText("Hello World");

            int left   = 0;
            int top    = 0;
            int width  = 0;
            int height = 0;

            application.ActiveWindow.GetPoint(out left, out top, out width, out height, application.Selection.Range);

            MessageBox.Show(string.Format("GetPoint returns Left:{0} Top:{1} Width:{2} Height:{3}", left, top, width, height));

            application.Quit();
            application.Dispose();
        }
Exemple #29
0
 private static bool TryDisposeDocumentInspectorDocument(Word.Document document, object comProxy)
 {
     try
     {
         if (null != document && false == document.IsDisposed)
         {
             document.Dispose();
         }
         else if (null == document)
         {
             if (null != comProxy)
             {
                 Marshal.ReleaseComObject(comProxy);
             }
         }
         return(true);
     }
     catch
     {
         return(false);
     }
 }
        public List <string> CreateReportWord()
        {
            string        appStatus;
            string        strRet  = null;
            List <string> appList = new List <string>(); //函数执行状态+文件名

            //测试使用的是fristpage

            using (m_wordApp = new Word.Application())
            {
                m_wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                m_utils   = new Word.Tools.CommonUtils(m_wordApp);
                m_doc     = m_wordApp.Documents.Add();
                appStatus = "0";
                WriteReportBasicInfo();
                //WriteTestReport(ParmeterChemicalModels, physicalmodels, chemicalmodels, str);
                strRet = SaveFile();
                appList.Add(appStatus);
                appList.Add(strRet);
            }
            return(appList);
        }
Exemple #31
0
 public static void OpenTemplate()
 {
     try
     {
         // add a new document
         newDocument = wordApplication.Documents.Add(Path.GetFullPath(_templatePath));
     }
     catch (Exception ex)
     {
         logger.Log(LogLevel.Debug, ex.Message + " - " + ex.StackTrace);
         //MessageBox.Show("OpenTemplate: newDocument is null.", "OpenTemplate", MessageBoxButtons.OK, MessageBoxIcon.Stop);
     }
 }
Exemple #32
0
        public static void OpenDoc_to_View()
        {
            object missing = System.Reflection.Missing.Value;
            object readOnly = true;
            object isVisible = false;

            try
            {
                // add a new document
                newDocument = wordApplication.Documents.Open(@FilePath + "\\" + FileName + GetDefaultExtension(wordApplication), missing, readOnly, missing, missing, missing, missing, missing, missing, missing,
                    missing, isVisible, missing);
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Debug, ex.Message + " - " + ex.StackTrace);
                //MessageBox.Show("OpenDoc_to_View: newDocument is null.", "OpenDoc_to_View", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
Exemple #33
0
 public void Finally()
 {
     if (document != null)
     {
         document.Close();
         document.Dispose();
         document = null;
     }
     if (application != null)
     {
         application.Quit();
         application.Dispose();
         application = null;
     }
 }
Exemple #34
0
 public void Open(string file)
 {
     try
     {
         initializeWord();
         document = application.Documents.Open(file);
     }
     catch (Exception ex)
     {
         Finally();
         throw ex;
     }
 }