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; // 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); }
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(); }
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() { // 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); }
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; // 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 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 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 Word.Tools.CommonUtils utils = new Word.Tools.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); }
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(); // 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"); // save the document string documentFile = utils.File.Combine(HostApplication.RootDirectory, "Example03", 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 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); }
protected void Button1_Click(object sender, EventArgs e) { // start word and turn off msg boxes //Word.Application wordApplication = null;// = new Word.Application(); try { wordApplication = new Word.Application(); wordApplication.DisplayAlerts = WdAlertLevel.wdAlertsNone; wordApplication.Visible = false; // add a new document Object oDoc = sPathDocs + @"CVofertasAT02.doc"; Word.Document newDocument = wordApplication.Documents.Add(oDoc); ArrayList aList = new ArrayList(); aList.Add(new string[] { "Pepe", "111111111A", "GERENTE", "25/11/1949" }); aList.Add(new string[] { "María", "222222222B", "COMERCIAL", "15/02/1982" }); aList.Add(new string[] { "Nerea", "333333333C", "PROGRAMADOR SENIOR", "24/06/1972" }); aList.Add(new string[] { "Xabi", "444444444H", "PROGRAMADOR JUNIOR", "14/01/1981" }); //Crea un rango en base al bookmark "MkDatosPersonales" Word.Range rngDP = newDocument.Bookmarks["MkDatosPersonales"].Range; CargarDatosPersonales(rngDP, (string[])aList[0]); Word.Range rngFA = newDocument.Bookmarks["MkTablaFormacionAcademica"].Range; CargarFormacionAcademica(rngFA, aList); /* * //Copia el "contenido" de la tabla (incluída) de la primera tabla (comienza índice 1) del bookmark "Tabla01" * Word.Range tblrng = newDocument.Bookmarks["Tabla02"].Range.Tables[1].Range; * tblrng.Copy(); * * * Word.Selection currentSelection; * * for (int i = 0; i < aList.Count; i++) * { * if (i == 0) //la tabla existente y copiada * { * ReemplazarDatos(tblrng, (string[])aList[i]); * } * else //resto de tablas pegadas * { * //Redimensiona/reposiciona el rango dos caracteres después, con el mismo inicio y final * rng.SetRange(rng.End + 2, rng.End + 2); * //y se selecciona el rango * rng.Select(); * //Como se ha establecido el mismo inicio y final, el rango seleccionado es un punto de inserción * currentSelection = wordApplication.Selection; * // Test to see if selection is an insertion point. * if (currentSelection.Type == WdSelectionType.wdSelectionIP) * { * currentSelection.TypeParagraph(); * } * * //Redimensiona/reposiciona el rango dos caracteres después, con el mismo inicio y final * rng.SetRange(rng.End + 2, rng.End + 2); * //y se selecciona el rango * // rng.Select(); * //Pegamos el rango copiado anteriormente, que contiene la tabla. * rng.Paste(); * //rng.Select(); * ReemplazarDatos(rng, (string[])aList[i]); * } * } */ //Para que borre los marcadores que pudiera haber. foreach (Word.Bookmark bkmk in newDocument.Bookmarks) { bkmk.Delete(); } // we save the document as .doc for compatibility with all word versions string documentFile = string.Format("{0}\\Prueba{1}", sPathDocs, ".doc"); double wordVersion = Convert.ToDouble(wordApplication.Version, CultureInfo.InvariantCulture); if (wordVersion >= 12.0) { newDocument.SaveAs(documentFile, WdSaveFormat.wdFormatDocumentDefault); } else { newDocument.SaveAs(documentFile); } Response.ClearContent(); Response.ClearHeaders(); Response.Buffer = true; Response.AddHeader("Content-Disposition", "attachment; filename=\"" + "Prueba.doc" + "\""); Response.BinaryWrite(SUPER.Capa_Negocio.Utilidades.FileToByteArray(documentFile)); Response.Flush(); //Response.Close(); //Response.End(); } catch (Exception) { } finally { // close word and dispose reference if (wordApplication != null) { wordApplication.Quit(); wordApplication.Dispose(); } } }
private void ExecuteEvents(Timeline timeline, TimelineHandler handler) { try { foreach (TimelineEvent timelineEvent in handler.TimeLineEvents) { try { _log.Trace($"Word event - {timelineEvent}"); WorkingHours.Is(handler); if (timelineEvent.DelayBefore > 0) { Thread.Sleep(timelineEvent.DelayBefore); } if (timeline != null) { System.Collections.Generic.List <int> pids = ProcessManager.GetPids(ProcessManager.ProcessNames.Word).ToList(); if (pids.Count > timeline.TimeLineHandlers.Count(o => o.HandlerType == HandlerType.Word)) { return; } } // start word and turn off msg boxes Word.Application wordApplication = new Word.Application { DisplayAlerts = WdAlertLevel.wdAlertsNone, Visible = true }; // add a new document Word.Document newDocument = wordApplication.Documents.Add(); try { wordApplication.WindowState = WdWindowState.wdWindowStateMinimize; foreach (Word.Document item in wordApplication.Documents) { item.Windows[1].WindowState = WdWindowState.wdWindowStateMinimize; } } catch (Exception e) { _log.Trace($"Could not minimize: {e}"); } // insert some text System.Collections.Generic.List <string> list = RandomText.GetDictionary.GetDictionaryList(); RandomText rt = new RandomText(list.ToArray()); rt.AddContentParagraphs(1, 1, 1, 10, 50); wordApplication.Selection.TypeText(rt.Content); int writeSleep = ProcessManager.Jitter(100); Thread.Sleep(writeSleep); wordApplication.Selection.HomeKey(WdUnits.wdLine, WdMovementType.wdExtend); wordApplication.Selection.Font.Color = WdColor.wdColorSeaGreen; wordApplication.Selection.Font.Bold = 1; wordApplication.Selection.Font.Size = 18; string rand = RandomFilename.Generate(); string dir = timelineEvent.CommandArgs[0].ToString(); if (dir.Contains("%")) { dir = Environment.ExpandEnvironmentVariables(dir); } if (Directory.Exists(dir)) { Directory.CreateDirectory(dir); } string path = $"{dir}\\{rand}.docx"; //if directory does not exist, create! _log.Trace($"Checking directory at {path}"); DirectoryInfo f = new FileInfo(path).Directory; if (f == null) { _log.Trace($"Directory does not exist, creating directory at {f.FullName}"); Directory.CreateDirectory(f.FullName); } try { if (File.Exists(path)) { File.Delete(path); } } catch (Exception e) { _log.Debug(e); } newDocument.Saved = true; newDocument.SaveAs(path); Report(handler.HandlerType.ToString(), timelineEvent.Command, timelineEvent.CommandArgs[0].ToString()); FileListing.Add(path); if (timelineEvent.DelayAfter > 0) { //sleep and leave the app open _log.Trace($"Sleep after for {timelineEvent.DelayAfter}"); Thread.Sleep(timelineEvent.DelayAfter - writeSleep); } wordApplication.Quit(); wordApplication.Dispose(); wordApplication = null; try { Marshal.ReleaseComObject(wordApplication); } catch { } try { Marshal.FinalReleaseComObject(wordApplication); } catch { } GC.Collect(); } catch (Exception e) { _log.Debug(e); } finally { Thread.Sleep(5000); } } } catch (Exception e) { _log.Error(e); } finally { KillApp(); _log.Trace($"Word closing..."); } }
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); }
protected void Page_Load(object sender, EventArgs e) { sPathDocs = Request.PhysicalApplicationPath + "Capa_Presentacion\\Pruebas\\Word\\docs\\"; // start word and turn off msg boxes //Word.Application wordApplication = null;// = new Word.Application(); try { wordApplication = new Word.Application(); wordApplication.DisplayAlerts = WdAlertLevel.wdAlertsNone; wordApplication.Visible = true; // add a new document Object oDoc = sPathDocs + @"CVofertasAT02.doc"; newDocument = wordApplication.Documents.Add(oDoc); DataSet ds = SUPER.DAL.Curriculum.ObtenerProfParaCVWord02(null, "1568", false, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); //Crea un rango en base al bookmark "MkDatosPersonales" Word.Range rngDP = newDocument.Bookmarks["MkDatosPersonales"].Range; //CargarDatosPersonales(rngDP, (string[])aList[0]); CargarDatosPersonales(rngDP, ds.Tables["DatosPersonales"].Rows[0]); Word.Range rngFA = newDocument.Bookmarks["MkTablaFormacionAcademica"].Range; DataView dvFA = new DataView(ds.Tables["FormacionAcademica"], "t001_idficepi = " + ds.Tables["DatosPersonales"].Rows[0]["t001_idficepi"].ToString(), "t001_idficepi", DataViewRowState.CurrentRows); //CargarFormacionAcademica(rngFA, aList); CargarFormacionAcademica(rngFA, dvFA); Word.Range rngCER = newDocument.Bookmarks["MkTablaCertificaciones"].Range; DataView dvCER = new DataView(ds.Tables["Certificados"], "t001_idficepi = " + ds.Tables["DatosPersonales"].Rows[0]["t001_idficepi"].ToString(), "t001_idficepi", DataViewRowState.CurrentRows); CargarCertificados(rngCER, dvCER); Word.Range rngEXP = newDocument.Bookmarks["MkTablaExperiencia"].Range; DataView dvEXP = new DataView(ds.Tables["Experiencia"], "t001_idficepi = " + ds.Tables["DatosPersonales"].Rows[0]["t001_idficepi"].ToString(), "t001_idficepi", DataViewRowState.CurrentRows); CargarExperiencias(rngEXP, dvEXP); Word.Range rngIDI = newDocument.Bookmarks["MkTablaIdioma"].Range; DataView dvIDI = new DataView(ds.Tables["Idiomas"], "t001_idficepi = " + ds.Tables["DatosPersonales"].Rows[0]["t001_idficepi"].ToString(), "t001_idficepi", DataViewRowState.CurrentRows); CargarIdiomas(rngIDI, dvIDI); Word.Range rngComPer = newDocument.Bookmarks["MkCompetenciasPersonales"].Range; DataView dvComPer = new DataView(ds.Tables["CompetenciasPersonales"], "t001_idficepi = " + ds.Tables["DatosPersonales"].Rows[0]["t001_idficepi"].ToString(), "t001_idficepi", DataViewRowState.CurrentRows); CargarCompeteciasPersonales(rngComPer, dvComPer); Word.Range rngComTec = newDocument.Bookmarks["MkCompetenciasTecnicas"].Range; DataView dvComTec = new DataView(ds.Tables["CompetenciasTecnicas"], "t001_idficepi = " + ds.Tables["DatosPersonales"].Rows[0]["t001_idficepi"].ToString(), "t001_idficepi", DataViewRowState.CurrentRows); CargarCompeteciasTecnicas(rngComTec, dvComTec); //Para que borre los marcadores que pudiera haber. foreach (Word.Bookmark bkmk in newDocument.Bookmarks) { bkmk.Delete(); } // we save the document as .doc for compatibility with all word versions documentFile = string.Format("{0}Prueba{1}", sPathDocs, ".doc"); double wordVersion = Convert.ToDouble(wordApplication.Version, CultureInfo.InvariantCulture); if (wordVersion >= 12.0) { newDocument.SaveAs(documentFile, WdSaveFormat.wdFormatDocumentDefault); } else { newDocument.SaveAs(documentFile); } ds.Dispose(); } catch (Exception) { bErrores = true; } finally { // close word and dispose reference if (wordApplication != null) { wordApplication.Documents.Close(Word.Enums.WdSaveOptions.wdDoNotSaveChanges); wordApplication.Quit(); wordApplication.Dispose(); } } if (!bErrores) { Response.ClearContent(); Response.ClearHeaders(); Response.Buffer = true; Response.AddHeader("Content-Disposition", "attachment; filename=\"" + "Prueba.doc" + "\""); Response.BinaryWrite(SUPER.Capa_Negocio.Utilidades.FileToByteArray(documentFile)); Response.Flush(); Response.Close(); Response.End(); } }
protected void runRepeatDoc() { wordApplication = new Word.Application(); wordApplication.DisplayAlerts = WdAlertLevel.wdAlertsNone; newDocument = wordApplication.Documents.Add(); Word.Table table = newDocument.Tables.Add(wordApplication.Selection.Range, 2, 1); table.Cell(1, 1).Select(); string mylongtextstring = (@"Title: A one sentence descriptive title for the issue Description: A detailed description of the issue, including the failure and reasoning. Steps to Recreate: Go to URL: " + txtURL + @" Log in with valid details Environment: Device - Device used during the testing Operating System - The operating system used during the testing Browser - The web browser used during the testing Firmware - Firmware version of the device if relevant Login Details for Account used - Add login details if applicable Supporting material: Add where appropriate screenshots, log files etc to aid detection of the issue and its correction. Version: " + txtURL + @" Date: " + DateTime.Now.ToString(@"dd/MM/yyyy") + @" Severity: "); wordApplication.Selection.TypeText(mylongtextstring); wordApplication.Selection.MoveDown(); wordApplication.Selection.MoveDown(); wordApplication.Selection.TypeParagraph(); Word.Table table2 = newDocument.Tables.Add(wordApplication.Selection.Range, 4, 1); table2.Cell(1, 1).Select(); string temp4s = (@"1. Blocking Issue/Crash 2. Major Impact on Functionality 3. Minor Impact on Functionality 4. Cosmetic Issue/Typo 5. Feature Enhancement/Suggestion"); wordApplication.Selection.TypeText(temp4s); table2.Cell(2, 1).Select(); temp4s = (@"Issue verified as fixed - " + DateTime.Now.ToString(@"dd/MM/yyyy") + @" Version: " + txtURL); wordApplication.Selection.TypeText(temp4s); table2.Cell(3, 1).Select(); temp4s = (@"Issue verified as not fixed - " + DateTime.Now.ToString(@"dd/MM/yyyy") + @" Version: " + txtURL); wordApplication.Selection.TypeText(temp4s); table2.Cell(4, 1).Select(); temp4s = (@"Closing issue based on above Comments - " + DateTime.Now.ToString(@"dd/MM/yyyy") + @" Version: " + txtURL); wordApplication.Selection.TypeText(temp4s); String bobone = wordApplication.Version; if (bobone == "14.0") { table.Style = "Table Grid"; table.ApplyStyleFirstColumn = false; table.ApplyStyleHeadingRows = false; table2.Style = "Table Grid"; table2.ApplyStyleFirstColumn = false; table2.ApplyStyleHeadingRows = false; } else { table.Style = "Table Grid"; table.ApplyStyleFirstColumn = false; table.ApplyStyleHeadingRows = false; table2.Style = "Table Grid"; table2.ApplyStyleFirstColumn = false; table2.ApplyStyleHeadingRows = false; } string documentFile = tempLocString; 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(); }