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(); } } }
/// <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); }
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); }
static void Main(string[] args) { Word.Application application = null; try { application = new Word.Application(); application.DisplayAlerts = WdAlertLevel.wdAlertsNone; object basic = application.WordBasic; object[] argValues = { 1 }; basic.GetType().InvokeMember("DisableAutoMacros", BindingFlags.InvokeMethod, null, basic, argValues, null, null, null); Console.WriteLine("Fine"); } catch (Exception exception) { Console.WriteLine(exception); } finally { if (null != application) { application.Quit(); application.Dispose(); } } Console.ReadKey(); }
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(); } } }
private string SaveFile() { string fileName = ""; string name = "合同模板样例" + DateTime.Now.ToFileTime(); // string documentFile = m_utils.File.Combine("c:\\", name, Word.Tools.DocumentFormat.Normal); string path = "d://DKLdownload"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string documentFile = m_utils.File.Combine(path, "合同模板样例", Word.Tools.DocumentFormat.Normal); if (FileSatus.FileIsOpen(documentFile) == 1) { //close the doc file } else { // fileName = documentFile;//.Replace(".docx", ".doc"); fileName = documentFile.Replace(".docx", ".doc"); //如果出现文件损坏就用上边那个 m_doc.SaveAs(fileName); m_wordApp.Quit(); //if(!string.IsNullOrEmpty(fileName)) // System.Diagnostics.Process.Start(fileName); } return(fileName); }
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); }
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) { } }
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 } }
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 } }
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); }
/// <summary> /// Convert to docx or PDF by using "NetOffice - MS Office in .NET", which uses Word application internal /// without version limitations. /// Note: /// http://netoffice.codeplex.com/ /// You need to add NetOffice.dll and WordApi.dll "References". /// To avoid error CS1752: Interop type 'Application' cannot be embedded. Use the applicable interface instead, /// in your Project, expand the "References", find the NetOffice and WordApi reference. /// Right click it and select properties, and change "Embed Interop Types" to false. /// </summary> /// <param name="fromFilePath"></param> /// <param name="toFilePath"></param> /// <param name="format"></param> private static void ConvertFormatByNetOffice(string fromFilePath, string toFilePath, WdSaveFormat format) { Word.Application wordApplication = new Word.Application() { DisplayAlerts = WdAlertLevel.wdAlertsNone }; var currentDoc = wordApplication.Documents.Open(fromFilePath); //var currentDoc = wordApplication.Documents.Add(); //Range _range = currentDoc.Range(); //_range.Text = @"Celsius = \sqrt(x+y) + sin(5/9 \times (Fahrenheit – 23 (\delta)^2))"; //foreach( var ac in wordApplication.OMathAutoCorrect.Entries) //{ // if (_range.Text.Contains(ac.Name)) // { // _range.Text = _range.Text.Replace(ac.Name, ac.Value); // } //} //currentDoc.OMaths.Add(_range); //var oMaths = _range.OMaths[1]; //oMaths.BuildUp(); //currentDoc.SaveAs(@"d:\temp\test\test.html", WdSaveFormat.wdFormatHTML, Type.Missing, Type.Missing, false, Type.Missing, null, false); currentDoc.SaveAs(toFilePath, format); currentDoc.Close(); wordApplication.Quit(); }
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(); } }
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."); }
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(); } } }
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); }
private void buttonQuitExample_Click(object sender, EventArgs e) { _wordApplication.Quit(); _wordApplication.Dispose(); buttonStartExample.Enabled = true; buttonQuitExample.Enabled = false; }
// 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 LoadFile(String path) { using(var wordApplication = new Word.Application()) { Word.Document newDocument = wordApplication.Documents.Open(path); _text = newDocument.Content.Text; wordApplication.Quit(); } }
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(); } }
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(); } }); }
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); }
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(); } } }
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 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); }
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(); } } }
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(); } } }
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(); }
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); }
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); }
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); }
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(); } } }
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(); }
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(); } } }
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); }
private static void TestWord() { Console.WriteLine("Test Word Application Utils"); Word.Application application = new Word.Application(); application.DisplayAlerts = Word.Enums.WdAlertLevel.wdAlertsNone; application.Documents.Add(); Word.Tools.Utils.CommonUtils utils = new Word.Tools.Utils.CommonUtils(application); int hwnd = utils.Application.TryGetMainWindowHandle(application.Documents[1]); application.Quit(); application.Dispose(); if (0 == hwnd) { throw new Exception("Cant resolve word hwnd"); } }
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(); } } }
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(); }
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(); }
private void btnSave_Click(object sender, EventArgs e) { DialogResult dialogResult = MessageBox.Show("Do you want to exit and save this test?", "Save Test", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.No) { return; } this.ucTimer.Stop(); ShowLoading(); try { switch (this.Test.OfficeApp) { case "Word": Word.Application application = this.Application as Word.Application; application.Quit(Word.Enums.WdSaveOptions.wdSaveChanges); application.Dispose(); break; case "Excel": break; case "PowerPoint": break; } this.Task.IsCompleted = false; this.Task.UsedTime = this.ucTimer.Current; Repository.updateTask(this.Task); CloseLoading(); this.Close(); } catch (Exception ex) { log.Error(ex.Message); log.Error("Save - " + Test.ToString()); } }
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); }
private static async void SpellCheckerDemo(Word.Application app) { app.Visible = true; var doc = app.Documents.Add(); doc.Words.First.InsertBefore("Here's some text that requiires speell cheking"); var process = GetProcess(app); var task = new Task(() => CheckSpellingTask(doc)); task.Start(); //Wait for the window to open Thread.Sleep(4000); //I found the classname by comparing the list of windows for the process before and after opening the spell checker //Then I checked the title to confirm var spellCheckerWindow = WindowStuff.GetWindowsWithPID(process.Id).FirstOrDefault(w => w.ClassName == "bosa_sdm_msword"); //Do something with the window spellCheckerWindow.Close(); //Wait for the task to finish before closing task.Wait(); doc.Close(false); app.Quit(); }
public TestResult DoTest() { Word.Application application = null; DateTime startTime = DateTime.Now; try { application = COMObject.Create <Word.Application>(COMObjectCreateOptions.CreateNewCore); 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(); } } }
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); }
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(); } } }
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(); } } }
public void Quit() { switch (_officeApp) { case "Excel": _excelApplication.Quit(); break; case "Word": _wordApplication.Quit(); break; case "Outlook": _outlookApplication.Quit(); break; case "Power Point": _powerpointApplication.Quit(); break; case "Access": _accessApplication.Quit(); break; case "Project": _projectApplication.Quit(); break; case "Visio": _visioApplication.Quit(); break; default: throw new ArgumentOutOfRangeException("officeApp"); } }
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(); } } }
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(); } } }
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); }
private static void TestWord() { Console.WriteLine("Test Word Application Utils"); Word.Application application = new Word.Application(); application.DisplayAlerts = Word.Enums.WdAlertLevel.wdAlertsNone; application.Documents.Add(); Word.Tools.Utils.CommonUtils utils = new Word.Tools.Utils.CommonUtils(application); int hwnd = utils.Application.TryGetMainWindowHandle(application.Documents[1]); application.Quit(); application.Dispose(); if (0 == hwnd) throw new Exception("Cant resolve word hwnd"); }
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(); } } }
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; // 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; // we save the document as .doc for compatibility with all word versions string documentFile = string.Format("{0}\\Example04{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); }