Example #1
1
        public TestResult DoTest()
        {
            Word.Application application = null;
            DateTime startTime = DateTime.Now;
            try
            {
                application = new Word.Application();
                application.Visible = true;
                application.DisplayAlerts = Word.Enums.WdAlertLevel.wdAlertsNone;
                application.Documents.Add();

                Office.COMAddIn addin = (from a in application.COMAddIns where a.ProgId == "NOTestsMain.WordTestAddinCSharp" select a).FirstOrDefault();
                if (null == addin || null == addin.Object)
                    return new TestResult(false, DateTime.Now.Subtract(startTime), "NOTestsMain.WordTestAddinCSharp or addin.Object not found.", null, "");

                bool addinStatusOkay = false;
                string errorDescription = string.Empty;
                if (null != addin.Object)
                {
                    COMObject addinProxy = new COMObject(addin.Object);
                    addinStatusOkay = (bool)Invoker.Default.PropertyGet(addinProxy, "StatusOkay");
                    errorDescription = (string)Invoker.Default.PropertyGet(addinProxy, "StatusDescription");
                    addinProxy.Dispose();
                }

                if (addinStatusOkay)
                    return new TestResult(true, DateTime.Now.Subtract(startTime), "", null, "");
                else
                    return new TestResult(false, DateTime.Now.Subtract(startTime), string.Format("NOTestsMain.WordTestAddinCSharp Addin Status {0}", errorDescription), 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();
                }
            }
        }
Example #2
0
        protected void LoadFileOffice(int indexProject = 0)
        {
            try
            {
                switch (this.Test.OfficeApp)
                {
                case "Word":
                    Word.Application wordApp = this.Application as Word.Application;
                    if (wordApp.Documents.Count > 0)
                    {
                        wordApp.ActiveDocument.Close(Word.Enums.WdSaveOptions.wdSaveChanges);
                    }
                    wordApp.Documents.Open(this.WorkingFilePaths(indexProject));
                    break;

                case "Excel":
                    Excel.Application excelApp = this.Application as Excel.Application;
                    if (excelApp.Workbooks.Count > 0)
                    {
                        excelApp.ActiveWorkbook.Close(true);
                    }
                    excelApp.Workbooks.Open(WorkingFilePaths(indexProject));
                    break;

                case "PowerPoint":
                    break;
                }
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                log.Error("Loading Project - " + Test.ToString());
            }
        }
        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);
        }
Example #4
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();
            }
        }
Example #5
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();

            // 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);
        }
        public void CreateNewDoc(string docName)
        {
            // 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();

            // 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;

            string applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            // save the document
            string fileExtension = GetDefaultExtension(wordApplication);
            object documentFile =
                   string.Format("{0}\\" + docName + "{1}", applicationPath, fileExtension);
            newDocument.SaveAs(documentFile);

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

            Console.WriteLine("Document saved.");
        }
Example #7
0
        public void RunExample()
        {
            // create simple a csv-file as datasource
            string fileName = string.Format("{0}\\DataSource.csv", HostApplication.RootDirectory);
             
            // if file exists then delete
            if (File.Exists(fileName))
                File.Delete(fileName);

            File.AppendAllText(fileName, string.Format("{0},{1}{2}", "ProjectName", "ProjectLink", Environment.NewLine));
            File.AppendAllText(fileName, string.Format("{0},{1}{2}", "NetOffice", "http://netoffice.codeplex.com", Environment.NewLine));

            // 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();

            // define the document as mailmerge
            newDocument.MailMerge.MainDocumentType = WdMailMergeMainDocType.wdFormLetters;

            // open the datasource
            newDocument.MailMerge.OpenDataSource(fileName);

            // insert some text and the mailmergefields defined in the datasource
            wordApplication.Selection.TypeText("This test is brought to you by ");
            newDocument.MailMerge.Fields.Add(wordApplication.Selection.Range, "ProjectName");

            wordApplication.Selection.TypeText(" for more information and examples visit ");
            newDocument.MailMerge.Fields.Add(wordApplication.Selection.Range, "ProjectLink ");

            wordApplication.Selection.TypeText(" or click ");

            object adress = newDocument.MailMerge.DataSource.DataFields[2].Value;
            object screenTip = "click me if you want!";
            object displayText = "here";
            newDocument.Hyperlinks.Add(wordApplication.Selection.Range, adress, Missing.Value, screenTip, displayText, Missing.Value);

            // show the contents of the fields
            int wdToggle = 9999998;
            newDocument.MailMerge.ViewMailMergeFieldCodes = wdToggle;

            //do not show the fieldcodes
            wordApplication.ActiveWindow.View.ShowFieldCodes = false;

            // save the document
            string documentFile = utils.File.Combine(HostApplication.RootDirectory, "Example04", 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);
        }
Example #8
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();
                }
            }
        }
Example #9
0
        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();

            // 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;

            // we save the document as .doc for compatibility with all word versions
            string documentFile = string.Format("{0}\\Example01{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);
        }
Example #10
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);
        }
Example #11
0
        protected virtual void ResizeOfficeWindow()
        {
            Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;
            int       height      = Convert.ToInt32(workingArea.Height * 0.5);
            int       width       = Convert.ToInt32(workingArea.Width * 0.75);

            switch (this.Test.OfficeApp)
            {
            case "Word":
                Word.Application wordApp = this.Application as Word.Application;
                wordApp.WindowState = Word.Enums.WdWindowState.wdWindowStateNormal;
                wordApp.Top         = 0;
                wordApp.Left        = 0;
                wordApp.Height      = height;
                wordApp.Width       = width;
                break;

            case "Excel":
                Excel.Application excelApp = this.Application as Excel.Application;
                excelApp.WindowState = Excel.Enums.XlWindowState.xlNormal;
                excelApp.Top         = 0;
                excelApp.Left        = 0;
                excelApp.Height      = height;
                excelApp.Width       = width;
                break;

            case "PowerPoint":
                break;
            }
        }
Example #12
0
        protected void FrmClosed()
        {
            this.ParentForm.Show();
            (this.ParentForm as frmChooseTest).LoadTasks();
            try
            {
                switch (this.Test.OfficeApp)
                {
                case "Word":
                    Word.Application wordApp = this.Application as Word.Application;
                    wordApp?.Quit(Word.Enums.WdSaveOptions.wdDoNotSaveChanges);
                    wordApp?.Dispose();
                    break;

                case "Excel":
                    Excel.Application excelApp = this.Application as Excel.Application;
                    excelApp?.Quit();
                    excelApp?.Dispose();
                    break;

                case "PowerPoint":
                    break;
                }
            }
            catch (Exception)
            { }
        }
Example #13
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
            }           
        }
Example #14
0
 private void button1_Click(object sender, EventArgs e)
 {
     _application         = new Word.ApplicationClass();
     _application.Visible = true;
     _application.Documents.Add();
     _application.Selection.TypeText("Hello World!");
     _application.DocumentBeforeCloseEvent += new NetOffice.WordApi.Application_DocumentBeforeCloseEventHandler(_application_DocumentBeforeCloseEvent);
     button1.Enabled = false;
     button2.Enabled = true;
     button3.Enabled = true;
 }
Example #15
0
 private void button1_Click(object sender, EventArgs e)
 {
     _application = new Word.Application();
     _application.Visible = true;
     _application.Documents.Add();
     _application.Selection.TypeText("Hello World!");
     _application.DocumentBeforeCloseEvent += new NetOffice.WordApi.Application_DocumentBeforeCloseEventHandler(_application_DocumentBeforeCloseEvent);
     button1.Enabled = false;
     button2.Enabled = true;
     button3.Enabled = true;
 }
        public void LoadFile(String path)
        {
            using(var wordApplication = new Word.Application())
            {
                Word.Document newDocument = wordApplication.Documents.Open(path);

                _text = newDocument.Content.Text;

                wordApplication.Quit();
            }
        }
Example #17
0
 public void ConvertToPDF(string inputFilePath, string outputFilePath)
 {
     using (Word.Application wordApp = new Word.Application())
     {
         wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
         var doc = wordApp.Documents.Open(inputFilePath);
         doc.SaveAs(outputFilePath, fileFormat: WdExportFormat.wdExportFormatPDF);
         doc.TablesOfContents[0]?.Update();
         wordApp.Quit(saveChanges: false);
         wordApp.Dispose();
     }
 }
Example #18
0
 void IDTExtensibility2.OnConnection(object Application, ext_ConnectMode ConnectMode, object AddInInst, ref Array custom)
 {
     try
     {
         _wordApplication = new Word.Application(null, Application);
     }
     catch (Exception exception)
     {
         string message = string.Format("An error occured.{0}{0}{1}", Environment.NewLine, exception.Message);
         MessageBox.Show(message, _prodId, MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
        private async Task<PDFFiles> convertDocToPDF(string destinationFile, bool deleteOiginal)
        {
            return await Task.Run(() =>
            {
                if (!Directory.GetParent(destinationFile).Exists) return null;

                string filePath = this.filePath;
                FileInfo file = new FileInfo(filePath);
                if (this.IsFileLocked()) throw new Exception("File: \"" + this.fileName + "\" is open in another application and cannot be merged"); 

                //read doc
                Word.Application wordApp = null;
                Word.Document doc = null;

                try
                {
                    wordApp = new Word.Application();
                    wordApp.DisplayAlerts = NetOffice.WordApi.Enums.WdAlertLevel.wdAlertsNone;          //disable ms word alerts
                    wordApp.Visible = false;

                    doc = wordApp.Documents.Open(filePath, Type.Missing, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing, Type.Missing, false, Type.Missing,
                        Type.Missing, Type.Missing, Type.Missing);

                    doc.Protect(WdProtectionType.wdNoProtection);

                    doc.SaveAs(destinationFile, WdSaveFormat.wdFormatPDF);

                    return new PDFFiles(destinationFile);

                }
                catch (Exception ex)
                {
                    this.convertionErrorMsg = ex.Message;
                    throw ex;
                }
                catch
                {                    
                    throw;
                }
                finally
                {
                    doc.Close(saveChanges: false);
                    doc.Dispose();
                    wordApp.Quit();
                    wordApp.Dispose();
                    GC.Collect();
                    if (deleteOiginal) this.delete();
                }
            });

        }      
Example #20
0
 private void button3_Click(object sender, EventArgs e)
 {
     if (null != _application)
     {
         _cancelClose = false;
         _application.Documents[1].Close(false);
         _application.Quit();
         _application.Dispose();
         _application    = null;
         button1.Enabled = true;
         button2.Enabled = false;
         button3.Enabled = false;
     }
 }
        public static void ConvertToDocx(Application instance, string file)
        {
            instance.DisplayAlerts = WdAlertLevel.wdAlertsNone;

            var doc = instance.Documents.Open(file, null, true);
            var extName = ".docx";

            var newName = Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file) + extName);
            doc.SaveAs2(newName, WdSaveFormat.wdFormatXMLDocument, null, null, null, null, null, null, null, null,
                null, null,
                null, null, null, null, WdCompatibilityMode.wdCurrent);
            //necessary
            doc.Close();
        }
Example #22
0
 private void button3_Click(object sender, EventArgs e)
 {
     if (null != _application)
     {
         _cancelClose = false;
         _application.Documents[1].Close(false);
         _application.Quit();
         _application.Dispose();
         _application = null;
         button1.Enabled = true;
         button2.Enabled = false;
         button3.Enabled = false;
     }
 }
Example #23
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();
                }
            }
        }
Example #24
0
    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();
    }
Example #25
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();
                }
            }
        }
Example #26
0
        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);
        }
Example #27
0
 public static bool Test_for_Word()
 {
     bool bol_Word = false;
     try
     {
         // System.IO.FileNotFoundException
         wordApplication = new _Word.Application();
         logger.Log(LogLevel.Info, LogCodeStatic("Word Version: " + wordApplication.Version + " is installed."));
         bol_Word = true;
         CloseWord();
     }
     catch
     {
         bol_Word = false;
     }
     return bol_Word;
 }
Example #28
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);
        }
Example #29
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();
        }
Example #30
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();

                // 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();
                }
            }
        }
Example #31
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", Word.Tools.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 dialog for the user(you!)
            HostApplication.ShowFinishDialog(null, documentFile);
        }
Example #32
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();
        }
Example #33
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);
        }
Example #34
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();
                    application.Dispose();
                }
            }
        }
Example #35
0
        public TestResult DoTest()
        {
            Word.Application application = null;
            DateTime startTime = DateTime.Now;
            try
            {
                application = new Word.Application();
                Word.Document document = application.Documents.Add();
                application.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                application.Selection.TypeText("Test with TabIntend C#");
                application.Selection.Start = 0;
                Word.Paragraph p = document.Application.Selection.Range.Paragraphs[1];

                p.IndentCharWidth(10);
                p.IndentFirstLineCharWidth(8);
                p.Space1();
                p.Space15();
                p.Space2();
                p.TabHangingIndent(5);
                p.TabIndent(3);

                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();
                }
            }
        }
Example #36
0
        private void buttonStartExample_Click(object sender, EventArgs e)
        {
            // start word and turn off msg boxes
            _wordApplication = new Word.Application();
            _wordApplication.DisplayAlerts = WdAlertLevel.wdAlertsNone;

            Office.CommandBar commandBar = null;
            Office.CommandBarButton commandBarBtn = null;

            // add a new document
            _wordApplication.Documents.Add();

            Word.Template normalDotTemplate = GetNormalDotTemplate();
            _wordApplication.CustomizationContext = normalDotTemplate;

            // add a commandbar popup
            Office.CommandBarPopup commandBarPopup = (Office.CommandBarPopup)_wordApplication.CommandBars["Menu Bar"].Controls.Add(MsoControlType.msoControlPopup, MsoBarPosition.msoBarTop, System.Type.Missing, 1, true);
            commandBarPopup.Caption = "commandBarPopup";

            #region few words, how to access the picture
            /*
             you can see we use an own icon via .PasteFace()
             is not possible from outside process boundaries to use the PictureProperty directly
             the reason for is IPictureDisp: http://support.microsoft.com/kb/286460/de
             its not important is early or late binding or managed or unmanaged, the behaviour is always the same
             For example, a COMAddin running as InProcServer and can access the Picture Property
            */
            #endregion

            #region CommandBarButton

            // add a button to the popup
            commandBarBtn = (Office.CommandBarButton)commandBarPopup.Controls.Add(MsoControlType.msoControlButton, System.Type.Missing, System.Type.Missing, System.Type.Missing, true);
            commandBarBtn.Style = MsoButtonStyle.msoButtonIconAndCaption;
            commandBarBtn.Caption = "commandBarButton";
            Clipboard.SetDataObject(_hostApplication.DisplayIcon.ToBitmap());
            commandBarBtn.PasteFace();
            commandBarBtn.ClickEvent += new Office.CommandBarButton_ClickEventHandler(commandBarBtn_Click);

            #endregion

            #region Create a new toolbar

            // add a new toolbar
            commandBar = _wordApplication.CommandBars.Add("MyCommandBar", MsoBarPosition.msoBarTop, false, true);
            commandBar.Visible = true;

            // add a button to the toolbar
            commandBarBtn = (Office.CommandBarButton)commandBar.Controls.Add(MsoControlType.msoControlButton, System.Type.Missing, System.Type.Missing, System.Type.Missing, true);
            commandBarBtn.Style = MsoButtonStyle.msoButtonIconAndCaption;
            commandBarBtn.Caption = "commandBarButton";
            commandBarBtn.FaceId = 3;
            commandBarBtn.ClickEvent += new Office.CommandBarButton_ClickEventHandler(commandBarBtn_Click);

            // add a dropdown box to the toolbar
            commandBarPopup = (Office.CommandBarPopup)commandBar.Controls.Add(MsoControlType.msoControlPopup, System.Type.Missing, System.Type.Missing, System.Type.Missing, true);
            commandBarPopup.Caption = "commandBarPopup";

            // add a button to the popup, we use an own icon for the button
            commandBarBtn = (Office.CommandBarButton)commandBarPopup.Controls.Add(MsoControlType.msoControlButton, System.Type.Missing, System.Type.Missing, System.Type.Missing, true);
            commandBarBtn.Style = MsoButtonStyle.msoButtonIconAndCaption;
            commandBarBtn.Caption = "commandBarButton";
            Clipboard.SetDataObject(_hostApplication.DisplayIcon.ToBitmap());
            commandBarBtn.PasteFace();
            commandBarBtn.ClickEvent += new Office.CommandBarButton_ClickEventHandler(commandBarBtn_Click);

            #endregion

            #region Create a new ContextMenu

            // add a commandbar popup
            commandBarPopup = (Office.CommandBarPopup)_wordApplication.CommandBars["Text"].Controls.Add(MsoControlType.msoControlPopup, MsoBarPosition.msoBarTop, false, 1, true);
            commandBarPopup.Caption = "commandBarPopup";

            // add a button to the popup
            commandBarBtn = (Office.CommandBarButton)commandBarPopup.Controls.Add(MsoControlType.msoControlButton, System.Type.Missing, System.Type.Missing, System.Type.Missing, true);
            commandBarBtn.Style = MsoButtonStyle.msoButtonIconAndCaption;
            commandBarBtn.Caption = "commandBarButton";
            commandBarBtn.FaceId = 9;
            commandBarBtn.ClickEvent += new Office.CommandBarButton_ClickEventHandler(commandBarBtn_Click);

            #endregion

            normalDotTemplate.Saved = true;

            // make visible & set buttons
            _wordApplication.Visible = true;
            buttonStartExample.Enabled = false;
            buttonQuitExample.Enabled = true;
        }
Example #37
0
        public TestResult DoTest()
        {
            Word.Application application = null;
            DateTime startTime = DateTime.Now;
            try
            {
                application = new Word.Application();
                application.DisplayAlerts = WdAlertLevel.wdAlertsNone;

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

                // create a new listtemplate
                Word.ListTemplate template = newDocument.ListTemplates.Add(true, "NetOfficeListTemplate");

                //get the predefined listlevels (9)
                Word.ListLevels levels = template.ListLevels;

                // customize the first level of the list
                levels[1].NumberFormat = "%1.";

                // tab is used to change the level
                levels[1].TrailingCharacter = WdTrailingCharacter.wdTrailingTab;
                levels[1].NumberStyle = WdListNumberStyle.wdListNumberStyleArabic;
                levels[1].NumberPosition = 0;
                levels[1].Alignment = WdListLevelAlignment.wdListLevelAlignLeft;

                levels[1].TextPosition = application.CentimetersToPoints(0.63F);
                levels[1].TabPosition = application.CentimetersToPoints(0.63F);
                levels[1].ResetOnHigher = 0;
                levels[1].StartAt = 1;
                levels[1].LinkedStyle = "";
                levels[1].Font.Bold = 1;

                // customize the second level of the list
                levels[2].NumberFormat = "%1.%2.";

                // tab is used to change the level
                levels[2].TrailingCharacter = WdTrailingCharacter.wdTrailingTab;
                levels[2].NumberStyle = WdListNumberStyle.wdListNumberStyleArabic;

                // we want the numbers to appear under the first letter of the higher level
                levels[2].NumberPosition = application.CentimetersToPoints(0.63F);
                levels[2].Alignment = WdListLevelAlignment.wdListLevelAlignLeft;

                // and the text should indent a tab more on the right
                levels[2].TextPosition = application.CentimetersToPoints(1.4F);
                levels[2].TabPosition = application.CentimetersToPoints(1.4F);
                levels[2].ResetOnHigher = 0;
                levels[2].StartAt = 1;
                levels[2].LinkedStyle = "";
                levels[2].Font.Italic = 1;

                // apply the defined listtemplate to the selection
                application.Selection.Range.ListFormat.ApplyListTemplate(template, false, WdListApplyTo.wdListApplyToWholeList, WdDefaultListBehavior.wdWord9ListBehavior);

                //create a list
                application.Selection.TypeText("Welcoming");
                application.Selection.TypeParagraph();

                application.Selection.TypeText("Introduction");
                application.Selection.TypeParagraph();

                application.Selection.TypeText("Presentation");
                application.Selection.TypeParagraph();

                // execute the indent so the second level gets activated
                application.Selection.Range.ListFormat.ListIndent();

                application.Selection.TypeText("Top 1");
                application.Selection.TypeParagraph();

                application.Selection.TypeText("Top 2");
                application.Selection.TypeParagraph();

                application.Selection.TypeText("Top 3");
                application.Selection.TypeParagraph();

                // execute the outdent so the first level gets reactivated
                application.Selection.Range.ListFormat.ListOutdent();
                application.Selection.TypeText("Questions & Answers");

                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();
                }
            }
        }
Example #38
0
        public TestResult DoTest()
        {
            Word.Application application = null;
            DateTime startTime = DateTime.Now;
            try
            {
                application = new Word.Application();
                application.DisplayAlerts = WdAlertLevel.wdAlertsNone;

                // create simple a csv-file as datasource
                string fileName = string.Format("{0}\\DataSource.csv", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));

                // if file exists then delete
                if (File.Exists(fileName))
                    File.Delete(fileName);

                File.AppendAllText(fileName, string.Format("{0},{1}{2}", "ProjectName", "ProjectLink", Environment.NewLine));
                File.AppendAllText(fileName, string.Format("{0},{1}{2}", "NetOffice", "http://netoffice.codeplex.com/", Environment.NewLine));

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

                // define the document as mailmerge
                newDocument.MailMerge.MainDocumentType = WdMailMergeMainDocType.wdFormLetters;

                // open the datasource
                newDocument.MailMerge.OpenDataSource(fileName);

                // insert some text and the mailmergefields defined in the datasource
                application.Selection.TypeText("This test is brought to you by ");
                newDocument.MailMerge.Fields.Add(application.Selection.Range, "ProjectName");

                application.Selection.TypeText(" for more information and examples visit ");
                newDocument.MailMerge.Fields.Add(application.Selection.Range, "ProjectLink ");

                application.Selection.TypeText(" or click ");

                object adress = newDocument.MailMerge.DataSource.DataFields[2].Value;
                object screenTip = "click Tooltip";
                object displayText = "here";
                newDocument.Hyperlinks.Add(application.Selection.Range, adress, Type.Missing, screenTip, displayText, Type.Missing);

                // show the contents of the fields
                int wdToggle = 9999998;
                newDocument.MailMerge.ViewMailMergeFieldCodes = wdToggle;

                //do not show the fieldcodes
                application.ActiveWindow.View.ShowFieldCodes = false;

                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();
                }
            }
        }
Example #39
0
        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();

            // create a new listtemplate
            Word.ListTemplate template = newDocument.ListTemplates.Add(true, "NetOfficeListTemplate");

            //get the predefined listlevels (9)
            Word.ListLevels levels = template.ListLevels;

            // customize the first level of the list
            levels[1].NumberFormat = "%1.";

            // tab is used to change the level
            levels[1].TrailingCharacter = WdTrailingCharacter.wdTrailingTab;
            levels[1].NumberStyle = WdListNumberStyle.wdListNumberStyleArabic;
            levels[1].NumberPosition = 0;
            levels[1].Alignment = WdListLevelAlignment.wdListLevelAlignLeft;
            levels[1].TextPosition = wordApplication.CentimetersToPoints(0.63F);
            levels[1].TabPosition = wordApplication.CentimetersToPoints(0.63F);
            levels[1].ResetOnHigher = 0;
            levels[1].StartAt = 1;
            levels[1].LinkedStyle = "";
            levels[1].Font.Bold = 1;

            // customize the second level of the list
            levels[2].NumberFormat = "%1.%2.";

            // tab is used to change the level
            levels[2].TrailingCharacter = WdTrailingCharacter.wdTrailingTab;
            levels[2].NumberStyle = WdListNumberStyle.wdListNumberStyleArabic;

            // we want the numbers to appear under the first letter of the higher level
            levels[2].NumberPosition = wordApplication.CentimetersToPoints(0.63F);
            levels[2].Alignment = WdListLevelAlignment.wdListLevelAlignLeft;

            // and the text should indent a tab more on the right
            levels[2].TextPosition = wordApplication.CentimetersToPoints(1.4F);
            levels[2].TabPosition = wordApplication.CentimetersToPoints(1.4F);
            levels[2].ResetOnHigher = 0;
            levels[2].StartAt = 1;
            levels[2].LinkedStyle = "";
            levels[2].Font.Italic = 1;

            // apply the defined listtemplate to the selection
            wordApplication.Selection.Range.ListFormat.ApplyListTemplate(template, false,
                                     WdListApplyTo.wdListApplyToWholeList, WdDefaultListBehavior.wdWord9ListBehavior);

            //create a list
            wordApplication.Selection.TypeText("Welcoming");
            wordApplication.Selection.TypeParagraph();

            wordApplication.Selection.TypeText("Introduction");
            wordApplication.Selection.TypeParagraph();

            wordApplication.Selection.TypeText("Presentation");
            wordApplication.Selection.TypeParagraph();

            // execute the indent so the second level gets activated
            wordApplication.Selection.Range.ListFormat.ListIndent();

            wordApplication.Selection.TypeText("Top 1");
            wordApplication.Selection.TypeParagraph();

            wordApplication.Selection.TypeText("Top 2");
            wordApplication.Selection.TypeParagraph();

            wordApplication.Selection.TypeText("Top 3");
            wordApplication.Selection.TypeParagraph();

            // execute the outdent so the first level gets reactivated
            wordApplication.Selection.Range.ListFormat.ListOutdent();
            wordApplication.Selection.TypeText("Questions & Answers");

            // we save the document as .doc for compatibility with all word versions
            string documentFile = string.Format("{0}\\Example03{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);
        }
Example #40
0
        public TestResult DoTest()
        {
            Word.Application application = null;
            DateTime startTime = DateTime.Now;
            try
            {
                Bitmap iconBitmap = new Bitmap(System.Reflection.Assembly.GetAssembly(this.GetType()).GetManifestResourceStream("WordTestsCSharp.Test07.bmp"));
                application = new Word.Application();
                application.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                application.Documents.Add();

                Office.CommandBar commandBar;
                Office.CommandBarButton commandBarBtn;

                Word.Template normalDotTemplate = GetNormalDotTemplate(application);
                application.CustomizationContext = normalDotTemplate;

                // add a commandbar popup
                Office.CommandBarPopup commandBarPopup = (Office.CommandBarPopup)application.CommandBars["Menu Bar"].Controls.Add(MsoControlType.msoControlPopup, MsoBarPosition.msoBarTop, System.Type.Missing, 1, true);
                commandBarPopup.Caption = "commandBarPopup";

                #region CommandBarButton

                // add a button to the popup
                commandBarBtn = (Office.CommandBarButton)commandBarPopup.Controls.Add(MsoControlType.msoControlButton, System.Type.Missing, System.Type.Missing, System.Type.Missing, true);
                commandBarBtn.Style = MsoButtonStyle.msoButtonIconAndCaption;
                commandBarBtn.Caption = "commandBarButton";
                Clipboard.SetDataObject(iconBitmap);
                commandBarBtn.PasteFace();
                commandBarBtn.ClickEvent += new Office.CommandBarButton_ClickEventHandler(commandBarBtn_Click);

                #endregion

                #region Create a new toolbar

                // add a new toolbar
                commandBar = application.CommandBars.Add("MyCommandBar", MsoBarPosition.msoBarTop, false, true);
                commandBar.Visible = true;

                // add a button to the toolbar
                commandBarBtn = (Office.CommandBarButton)commandBar.Controls.Add(MsoControlType.msoControlButton, System.Type.Missing, System.Type.Missing, System.Type.Missing, true);
                commandBarBtn.Style = MsoButtonStyle.msoButtonIconAndCaption;
                commandBarBtn.Caption = "commandBarButton";
                commandBarBtn.FaceId = 3;
                commandBarBtn.ClickEvent += new Office.CommandBarButton_ClickEventHandler(commandBarBtn_Click);

                // add a dropdown box to the toolbar
                commandBarPopup = (Office.CommandBarPopup)commandBar.Controls.Add(MsoControlType.msoControlPopup, System.Type.Missing, System.Type.Missing, System.Type.Missing, true);
                commandBarPopup.Caption = "commandBarPopup";

                // add a button to the popup, we use an own icon for the button
                commandBarBtn = (Office.CommandBarButton)commandBarPopup.Controls.Add(MsoControlType.msoControlButton, System.Type.Missing, System.Type.Missing, System.Type.Missing, true);
                commandBarBtn.Style = MsoButtonStyle.msoButtonIconAndCaption;
                commandBarBtn.Caption = "commandBarButton";
                Clipboard.SetDataObject(iconBitmap);
                commandBarBtn.PasteFace();
                commandBarBtn.ClickEvent += new Office.CommandBarButton_ClickEventHandler(commandBarBtn_Click);

                #endregion

                #region Create a new ContextMenu

                // add a commandbar popup
                commandBarPopup = (Office.CommandBarPopup)application.CommandBars["Text"].Controls.Add(MsoControlType.msoControlPopup, MsoBarPosition.msoBarTop, false, 1, true);
                commandBarPopup.Caption = "commandBarPopup";

                // add a button to the popup
                commandBarBtn = (Office.CommandBarButton)commandBarPopup.Controls.Add(MsoControlType.msoControlButton, System.Type.Missing, System.Type.Missing, System.Type.Missing, true);
                commandBarBtn.Style = MsoButtonStyle.msoButtonIconAndCaption;
                commandBarBtn.Caption = "commandBarButton";
                commandBarBtn.FaceId = 9;
                commandBarBtn.ClickEvent += new Office.CommandBarButton_ClickEventHandler(commandBarBtn_Click);

                #endregion

                normalDotTemplate.Saved = true;

                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();
                }
            }
        }
Example #41
0
 private void CreateOfficeApplication()
 {
     switch (_officeApp)
     {
         case "Excel":
             _excelApplication = new Excel.Application("Excel.Application");
             break;
         case "Word":
             _wordApplication = new Word.Application("Word.Application");
             break;
         case "Outlook":
             _outlookApplication = new Outlook.Application("Outlook.Application");
             break;
         case "Power Point":
             _powerpointApplication = new PowerPoint.Application("PowerPoint.Application");
             break;
         case "Access":
             _accessApplication = new Access.Application("Access.Application");
             break;
         case "Project":
             _projectApplication = new Project.Application("MSProject.Application");
             break;
         case "Visio":
             _visioApplication = new Visio.Application("Visio.Application");
             break;
         default:
             throw new ArgumentOutOfRangeException("officeApp");
     }
 }