}// doc public MedicalModel AddFromFileDbFile(object path)// doc doctemplateservice { Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); object miss = System.Reflection.Missing.Value; object readOnly = true; Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); string allText = docs.Content.Text; string[] needTxt = allText.Split(new char[] { ' ', '\n', '\r' }); MedicalModel md = new MedicalModel { Complaints = GetDataFromDoc("Жалобы:", "Анамнез:", needTxt), Anamnes = GetDataFromDoc("Анамнез:", "ОбщийСтатус:", needTxt), StatusPraesens = GetDataFromDoc("ОбщийСтатус:", "МестныйСтатус:", needTxt), LocalStatus = GetDataFromDoc("МестныйСтатус:", "ПредварительныйДиагноз:", needTxt), Diagnos = GetDataFromDoc("ПредварительныйДиагноз:", "Рекомендации:", needTxt) }; docs.Close(); word.Quit(); return(md); }
/// <SUMMARY></SUMMARY> /// 创建文档 /// public void CreateAWord() { //实例化word应用对象 this._wordApplication = new Microsoft.Office.Interop.Word.ApplicationClass(); Object myNothing = System.Reflection.Missing.Value; this._wordDocument = this._wordApplication.Documents.Add(ref myNothing, ref myNothing, ref myNothing, ref myNothing); }
private void ReplaceWord(string ReplacedWord, string text, Microsoft.Office.Interop.Word.Document document) { var range = document.Content; range.Find.ClearFormatting(); range.Find.Execute(FindText: ReplacedWord, ReplaceWith: text); }
public void AddFromFile(ref TextBox textbox) { Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); object miss = System.Reflection.Missing.Value; object path = @"C:\Users\Husia\Documents\test.docx"; object readOnly = true; Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); string allText = docs.Content.Text; string[] needTxt = allText.Split(new char[] { ' ', '\n', '\r' }); string mytxt = ""; bool ok = false; for (int i = 0; i < needTxt.Length; i++) { if (ok) { mytxt += " " + needTxt[i]; } if (needTxt[i].ToLower() == "анамнез") { ok = true; } if (needTxt[i] == "статус") { ok = false; } } textbox.Text = mytxt; docs.Close(); word.Quit(); } //нет ссылок
private void cmboAllignSlot_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { var app = new Microsoft.Office.Interop.Word.Application(); var doc = new Microsoft.Office.Interop.Word.Document(); doc = app.Documents.Add(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "/Template1Bewerkt.docx"); //Hard gecodeerd vanuit template Section s = doc.Sections[6]; //Switch case om de uitlijning correct uit te voeren , Links staat er niet bij omdat dit "default" zo staat. switch (cmboAllignSlot.SelectedItem) { case "Rechts": s.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break; case "Centreren": s.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break; default: s.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break; } doc.SaveAs2(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "/Template1Bewerkt.docx"); doc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(app); }
} //нет ссылок public MedicalModel AddFromFileClass(object path) { Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); object miss = System.Reflection.Missing.Value; object readOnly = true; Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); string allText = docs.Content.Text; string[] needTxt = allText.Split(new char[] { ' ', '\n', '\r' }); MedicalModel md = new MedicalModel { Complaints = GetDataFromDoc("Жалобы:", "Anamnes:", needTxt), Anamnes = GetDataFromDoc("Anamnes:", "StatusPraesens:", needTxt), StatusPraesens = GetDataFromDoc("StatusPraesens:", "LocalStatus:", needTxt), LocalStatus = GetDataFromDoc("LocalStatus:", "Diagnos:", needTxt), Diagnos = GetDataFromDoc("Diagnos:", "Рекомендации:", needTxt) }; docs.Close(); word.Quit(); return(md); }// doc
private string SaveAsTextForPdx(string docxFilePath) { string content = string.Empty; object missing = System.Type.Missing; Microsoft.Office.Interop.Word.Application wApp = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document wDoc = null; try { // open word document wApp.Visible = false; wDoc = wApp.Documents.Open(docxFilePath, AddToRecentFiles: false); // remove custom xml part RemoveCustomXmlParts(wDoc); // process bookmark ProcessBookmarkForMhtFile(wDoc); content = Core.MarkupUtilities.GetRangeText(wDoc.Content); // close document ((Microsoft.Office.Interop.Word._Document)wDoc).Close(); } catch { } finally { ((Microsoft.Office.Interop.Word._Application)wApp).Quit(missing, missing, missing); System.Runtime.InteropServices.Marshal.ReleaseComObject(wDoc); System.Runtime.InteropServices.Marshal.ReleaseComObject(wApp); } return(content); }
void OpenFileWord(string fileLocation) { Microsoft.Office.Interop.Word.Application ap = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document document = ap.Documents.Open(fileLocation); PutStringIntoTable(document); ap.Visible = true; }
/// <summary> /// Copies a document to a specified path. /// </summary> /// <param name="document">The Document instance.</param> /// <param name="path">The path where the new file will be saved.</param> /// <param name="saveFormat">The save format.</param> /// <exception cref="IOException">When the file cannot be saved.</exception> /// <remarks>The document is saved in Unicode little endian encoding.</remarks> /// <returns>True if the operation succedes. False otherwise.</returns> public bool ShadowCopyDocument(Microsoft.Office.Interop.Word.Document document, string path, Microsoft.Office.Interop.Word.WdSaveFormat saveFormat) { DocumentCopier documentCopier = new DocumentCopier(document, path, saveFormat); documentCopier.Perform(); return(documentCopier.GetResults()); }
private void WelcomeText_Click(object sender, RoutedEventArgs e) { //Word app + document aanmaken + instellen in welk document gewerkt word. var app = new Microsoft.Office.Interop.Word.Application(); var doc = new Microsoft.Office.Interop.Word.Document(); doc = app.Documents.Add(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "/Template1Bewerkt.docx"); //Hard gecodeerde Sectie van template aanspreken. Section s = doc.Sections[4]; //Volledige "Afstand" van sectie bepalen. Range r = doc.Sections[4].Range; //Controleren of gebruiker zelf iets ingevuld heeft als text if (!TxtbxWelkomText.Text.Equals("")) { r.Text = TxtbxWelkomText.Text.Trim() + "\n\r"; } else { //Voor geprogrammeerde text voor alle sportclubs. r.Text = "Welkom beste leden bij het begin van het nieuwe jaar, we zijn blij om u nog steeds als lid te zien." + " We hebben natuurlijk nieuwe spullen nodig om het nieuw sportjaar goed in te zetten, dit vind u terug in de tabel hieronder.\n\r"; } //Maken dat de range van de ingetypte woorden niet afkapt. dus zelfs groote instellen r.SetRange(0, r.Text.Length); //toevoegen als paragraaf s.Range.Paragraphs.Add(r); //opslaan &sluiten doc.SaveAs2(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "/Template1Bewerkt.docx"); doc.Close(); //Dit om bepaalde achtergrond taken te stoppen. System.Runtime.InteropServices.Marshal.ReleaseComObject(app); }
//public void LeerPDF() //{ // Word2Pdf objWorPdf = new Word2Pdf(); // string backfolder1 = "D:\\DocTmp\\"; // string strFileName = "tmp.docx"; // object FromLocation = backfolder1 + "\\" + strFileName; // string FileExtension = Path.GetExtension(strFileName); // string ChangeExtension = strFileName.Replace(FileExtension, ".pdf"); // if (FileExtension == ".doc" || FileExtension == ".docx") // { // object ToLocation = backfolder1 + "\\" + ChangeExtension; // objWorPdf.InputLocation = FromLocation; // objWorPdf.OutputLocation = ToLocation; // objWorPdf.Word2PdfCOnversion(); // } //} public void LeerPDF() { Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); wordApp.Visible = false; // file from object filename = Server.MapPath("DocTmp/tmp.doc"); // input // file to object newFileName = Server.MapPath("DocTmp/tmp.pdf"); // output object missing = System.Type.Missing; // open document Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); // formt to save the file, this case PDF object formatoArquivo = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF; // save file doc.SaveAs(ref newFileName, ref formatoArquivo, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); doc.Close(ref missing, ref missing, ref missing); wordApp.Quit(ref missing, ref missing, ref missing); string script = "<script languaje='javascript'> "; script += "mostrarFichero('DocTmp/tmp.pdf') "; script += "</script>" + Environment.NewLine; Page.RegisterStartupScript("mostrarFichero", script); }
private void ReplaceBookmarkText(Microsoft.Office.Interop.Word.Document worddocument, ref string bookmarkName, string text) { var range = worddocument.Content; range.Find.ClearFormatting(); range.Find.Execute(FindText: bookmarkName, ReplaceWith: text); }
public void savedoc() { string loc = ""; SaveFileDialog open = new SaveFileDialog(); if (open.ShowDialog() == DialogResult.OK) { loc = open.FileName; } try { Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application(); winword.Visible = false; object missing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing); document.Content.Document.Content.Text = inputTextBox.Text + Environment.NewLine; object filename = loc; document.SaveAs2(ref filename); document.Close(ref missing, ref missing, ref missing); document = null; winword.Quit(ref missing, ref missing, ref missing); winword = null; // MessageBox.Show("DOC file is saved"); } catch (Exception ex) { MessageBox.Show("Error :" + ex.Message); } }
public void ReplaceWordStub(string stubToReplace, string text, Microsoft.Office.Interop.Word.Document wordDocument) { var range = wordDocument.Content; range.Find.ClearFormatting(); range.Find.Execute(FindText: stubToReplace, ReplaceWith: text); }
private void Merge() { System.Diagnostics.Stopwatch oTime = new System.Diagnostics.Stopwatch(); oTime.Start(); //建立一个空word用以存放合并后的文件 string filename = @"C:\DFS\" + SharedData.excelFile.Substring(SharedData.excelFile.LastIndexOf("\\") + 1, (SharedData.excelFile.LastIndexOf(".") - SharedData.excelFile.LastIndexOf("\\") - 1)) + ".doc"; object Nothing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); wordDoc.SpellingChecked = false; wordDoc.ShowSpellingErrors = false; Log.RecordLog("新建空白" + filename + "成功!等待合并word文档!"); SharedData.fileName = filename; wordDoc.SaveAs2(filename); wordDoc.Close(ref Nothing, ref Nothing, ref Nothing); wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); //合并各个word文件 wordDocumentMerger merger = new wordDocumentMerger(); merger.InsertMerge(groupName); oTime.Stop(); long time = oTime.ElapsedMilliseconds; Log.RecordLog(@"word合并完成,最终生成文件为 " + SharedData.fileName + " 耗时:" + (time / 1000).ToString() + "秒!"); //MessageBox.Show("word合并完成,耗时:" + (time / 1000).ToString() + "秒!"); }
//pega todas as linhas menos as com titulo informado public string DocReaderGetAllButTitle(string fileLocation, string headingText) { Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); object miss = System.Reflection.Missing.Value; object path = fileLocation; object readOnly = true; Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); string totaltext = ""; int paraCount = docs.Paragraphs.Count; for (int i = 1; i <= paraCount; i++) { if (docs.Paragraphs[i].Range.Text.ToString().TrimEnd('\r').ToUpper() != headingText.ToUpper()) { totaltext += " \r\n " + HttpUtility.HtmlDecode(docs.Paragraphs[i].Range.Text.ToString()); } } if (totaltext == "") { totaltext = "No such data found!"; } docs.Close(); word.Quit(); return(totaltext); }
private static void GerarArquivoPdf(string caminhoDoc, string caminhoPDF) { try { // Abrir Aplicacao Word Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); // Arquivo de Origem object filename = caminhoDoc; object newFileName = caminhoPDF; object missing = System.Type.Missing; // Abrir documento Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); // Formato para Salvar o Arquivo – Destino - No caso, PDF object formatoArquivo = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF; // Salvar Arquivo doc.SaveAs(ref newFileName, ref formatoArquivo, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); // Não salvar alterações no arquivo original object salvarAlteracoesArqOriginal = false; wordApp.Quit(ref salvarAlteracoesArqOriginal, ref missing, ref missing); } catch (Exception ex) { } }
/// <summary> /// 构造函数 /// </summary> /// <param name="template">模板文件位置</param> /// <param name="newWord">保存位置</param> public WordAPI(string template, string newWord) { this._template = template; this._newWord = newWord; wordApp = new Application(); documentType = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument; _wordDocument = wordApp.Documents.Add(ref _template, ref defaultV, ref documentType, ref defaultV); }
private static void closeDoc(Microsoft.Office.Interop.Word.Document doc) { object sch = Word.WdSaveOptions.wdDoNotSaveChanges; object aq = Type.Missing; object ab = Type.Missing; (doc as Microsoft.Office.Interop.Word._Document).Close(ref sch, ref aq, ref ab); }
private void wordToolStripMenuItem_Click(object sender, EventArgs e) { saveFileDialog2.Filter = "doc files (*.doc)|*.doc|All files (*.*)|*.*"; saveFileDialog2.FilterIndex = 2; saveFileDialog2.RestoreDirectory = true; if (saveFileDialog2.ShowDialog() == DialogResult.OK) { Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application(); Object missing = Type.Missing; Word.Document word1 = application.Documents.Add(ref missing, ref missing, ref missing, ref missing); //object text = "tesfsdfkslghsdgjh"; //word1.Paragraphs[1].Range.InsertParagraphAfter(); //word1.Paragraphs[1].Range.Text = "asaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; //word1.Footnotes.Location = Word.WdFootnoteLocation.wdBeneathText; //word1.Footnotes.NumberStyle = Word.WdNoteNumberStyle.wdNoteNumberStyleLowercaseRoman; //word1.Footnotes.Add(word1.Paragraphs[1].Range.Words[2].Characters[2], ref missing, ref text); Microsoft.Office.Interop.Word.Document doc = application.ActiveDocument; Microsoft.Office.Interop.Word.Range range = doc.Paragraphs[doc.Paragraphs.Count].Range; dataSetTemp = dbw1.ReadMetricsByReport(listView2.Items[listView2.SelectedIndices[0]].Text); doc.Tables.Add(range, dataSetTemp.Tables[0].Rows.Count + 1, 6, ref missing, ref missing); doc.Tables[1].Cell(1, 1).Range.Text = "NAME metric"; doc.Tables[1].Cell(1, 2).Range.Text = "MIN value"; doc.Tables[1].Cell(1, 3).Range.Text = "CUR value"; doc.Tables[1].Cell(1, 4).Range.Text = "MAX value"; doc.Tables[1].Cell(1, 5).Range.Text = "VALUE"; doc.Tables[1].Cell(1, 6).Range.Text = "RATE"; for (int i = 0; i < dataSetTemp.Tables[0].Rows.Count; i++) { dataSetTemp1 = dbw1.ReadInfoMetricByReportMetric(listView2.Items[listView2.SelectedIndices[0]].Text, dataSetTemp.Tables[0].Rows[i].ItemArray[0].ToString()); doc.Tables[1].Cell(i + 2, 1).Range.Text = dataSetTemp.Tables[0].Rows[i].ItemArray[0].ToString(); doc.Tables[1].Cell(i + 2, 2).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[2].ToString(); doc.Tables[1].Cell(i + 2, 3).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[0].ToString(); doc.Tables[1].Cell(i + 2, 4).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[3].ToString(); doc.Tables[1].Cell(i + 2, 5).Range.Text = Double.Parse(dataSetTemp1.Tables[0].Rows[0].ItemArray[4].ToString()).ToString("F5"); doc.Tables[1].Cell(i + 2, 6).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[5].ToString(); } doc.Tables[1].Columns.AutoFit(); Word.Border[] borders = new Word.Border[6]; Word.Table tbl = doc.Tables[doc.Tables.Count]; borders[0] = tbl.Borders[Word.WdBorderType.wdBorderLeft]; borders[1] = tbl.Borders[Word.WdBorderType.wdBorderRight]; borders[2] = tbl.Borders[Word.WdBorderType.wdBorderTop]; borders[3] = tbl.Borders[Word.WdBorderType.wdBorderBottom]; borders[4] = tbl.Borders[Word.WdBorderType.wdBorderHorizontal]; borders[5] = tbl.Borders[Word.WdBorderType.wdBorderVertical]; foreach (Word.Border border in borders) { border.LineStyle = Word.WdLineStyle.wdLineStyleSingle; border.Color = Word.WdColor.wdColorBlack; } application.Documents[word1].SaveAs(saveFileDialog2.FileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); application.Quit(); string info = "Doc file saved at\n" + saveFileDialog2.FileName; MessageBox.Show(this, info, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
/// <summary> /// 释放资源 /// </summary> private void disponse() { object missingValue = Type.Missing; object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges; ((Microsoft.Office.Interop.Word._Document)_wordDocument).Close(ref doNotSaveChanges); ((_Application)wordApp.Application).Quit(ref defaultV, ref defaultV, ref defaultV); _wordDocument = null; wordApp = null; }
/* * Creates a pdf copy of the word file * pdfFileName: Path and file name of the PDF file with the extension address on the desktop * pdfInFolder: Path and file name of the pdf file in the Folder */ public void convertToPDF() { Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); wordDoc = app.Documents.Open(fileToConvert, ReadOnly: true); wordDoc.ExportAsFixedFormat(saveToPath, WdExportFormat.wdExportFormatPDF); wordDoc.Close(WdSaveOptions.wdDoNotSaveChanges); app.Quit(); }
private void addPages(string docLoc, Word.Table oTable) { Microsoft.Office.Interop.Word.Application word = null; word = new Microsoft.Office.Interop.Word.Application(); object inputFile = docLoc; object confirmConversions = false; object readOnly = true; object visible = false; object missing = Type.Missing; // Open the document... Microsoft.Office.Interop.Word.Document tempDoc = null; tempDoc = word.Documents.Open( ref inputFile, ref confirmConversions, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref visible, ref missing, ref missing, ref missing, ref missing); tempDoc.Activate(); string tempPageString = ""; string tempPageRevisionText = ""; string tempPageDateText = ""; List <multiLOEP> pageMultiLOEP = new List <multiLOEP>(); for (int i = 1; i <= GetPageNumber(tempDoc); i++) { tempPageString = getString(tempDoc, "edocs_Page" + i + "_page"); tempPageRevisionText = getString(tempDoc, "edocs_Page" + tempPageString + "_rev"); tempPageDateText = getString(tempDoc, "edocs_Page" + tempPageString + "_date"); if (pageMultiLOEP.Count == 0) { pageMultiLOEP.Add(new multiLOEP(tempPageString, tempPageRevisionText, tempPageDateText)); } else if (pageMultiLOEP[pageMultiLOEP.Count - 1].rev != tempPageRevisionText) { if (addRows(oTable.Rows[oTable.Rows.Count], pageMultiLOEP[pageMultiLOEP.Count - 1])) { oTable.Rows.Add(); } pageMultiLOEP.Add(new multiLOEP(tempPageString, tempPageRevisionText, tempPageDateText)); } else { pageMultiLOEP[pageMultiLOEP.Count - 1].endPage = tempPageString; } } addRows(oTable.Rows[oTable.Rows.Count], pageMultiLOEP[pageMultiLOEP.Count - 1]); tempDoc.Close(null, null, null); word.Quit(null, null, null); word = null; GC.Collect(); System.Diagnostics.Debug.WriteLine("Finish Multi"); }
private void Changed_Lettertype(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { var app = new Microsoft.Office.Interop.Word.Application(); var doc = new Microsoft.Office.Interop.Word.Document(); doc = app.Documents.Add(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "/Template1Bewerkt.docx"); //Colledige content Font aanpassen naar geselecteerde waarde. doc.Content.Font.Name = CmboFontFamily.SelectedItem.ToString(); doc.SaveAs2(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "/Template1Bewerkt.docx"); doc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(app); }
/// <summary> /// 替换字符 /// </summary> /// <param name="oDoc"></param> /// <param name="FindText"></param> /// <param name="ReplaceWith"></param> /// <param name="MissingValue"></param> void ReplaceZF(Microsoft.Office.Interop.Word.Document oDoc, object FindText, object ReplaceWith, object MissingValue) { //wdReplaceAll - 替换找到的所有项。 //wdReplaceNone - 不替换找到的任何项。 //wdReplaceOne - 替换找到的第一项。 object Replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll; //移除Find的搜索文本和段落格式设置 oDoc.Content.Find.ClearFormatting(); oDoc.Content.Find.Execute(ref FindText, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref ReplaceWith, ref Replace, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); }
/// <summary> /// Performs the playback of actions in this module. /// </summary> /// <remarks>You should not call this method directly, instead pass the module /// instance to the <see cref="TestModuleRunner.Run(ITestModule)"/> method /// that will in turn invoke this method.</remarks> void ITestModule.Run() { Mouse.DefaultMoveTime = 300; Keyboard.DefaultKeyPressTime = 100; Delay.SpeedFactor = 1.0; // Word.Application word = null; // try // { // word = (Word.Application)Marshal.GetActiveObject("Word.Application"); // } // catch (COMException) // { // } // if (word == null) word = new Microsoft.Office.Interop.Word.Application(); // if(word == null) { /* report error */ } // // Ranorex.Report.Info("The current document is :" + word.ActiveDocument.FullName.ToString()); // Microsoft.Office.Interop.Word.Application WordObj; // WordObj = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application"); // for (int i = 0; i < WordObj.Windows.Count; i++) // { // object idx = i + 1; // var WinObj = WordObj.Windows.get_Item(ref idx); // Ranorex.Report.Info(WinObj.Document.FullName); // // } //Get handle to already opened Word doc using marshal service. Both Word & Ranorex must be //opened with Administrator permissions // // Word.Application objWord = System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application") as Word.Application; // // string docname = objWord.ActiveDocument.FullName; // // Ranorex.Report.Info(docname); //Get handle on exiting opened Word Doc (need to know name and path in advance) Word.Application objWord = new Microsoft.Office.Interop.Word.Application(); object missing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Document document = objWord.Documents.Open(@"C:\Users\edgewords\Documents\ChatLog Meet Now 2019_01_08 22_00.rtf", false, true, false, ref missing, ref missing, false); string docname = objWord.ActiveDocument.FullName; Ranorex.Report.Info(docname); }
protected string GetTextFromWord() { Object filename = fileName; Object confirmConversions = Type.Missing; Object readOnly = true; Object addToRecentFiles = Type.Missing; Object passwordDocument = Type.Missing; Object passwordTemplate = Type.Missing; Object revert = Type.Missing; Object writePasswordDocument = Type.Missing; Object writePasswordTemplate = Type.Missing; Object format = Type.Missing; Object encoding = Type.Missing; Object visible = Type.Missing; Object openConflictDocument = Type.Missing; Object openAndRepair = Type.Missing; Object documentDirection = Type.Missing; Object noEncodingDialog = Type.Missing; Word.Application Progr = new Microsoft.Office.Interop.Word.Application(); Progr.Documents.Open(ref filename, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openConflictDocument, ref openAndRepair, ref documentDirection, ref noEncodingDialog); Word.Document Doc = new Microsoft.Office.Interop.Word.Document(); Doc = Progr.Documents.Application.ActiveDocument; object start = 0; object stop = Doc.Characters.Count; Word.Range Rng = Doc.Range(ref start, ref stop); string Result = Rng.Text; object sch = Type.Missing; object aq = Type.Missing; object ab = Type.Missing; Progr.Quit(ref sch, ref aq, ref ab); return(Result); }
/// <summary> /// remove custom xml part (internal bookmark, osql, checksum, comment) /// </summary> /// <param name="wDoc"></param> private void RemoveCustomXmlParts(Microsoft.Office.Interop.Word.Document wDoc) { try { Pdwx.Services.WordHeper.RemoveProtectPassword(wDoc, ProtectLevel.All); // accept all changes try { if (wDoc.TrackRevisions) { wDoc.AcceptAllRevisions(); } } catch { } List <string> xmlPartIds = new List <string>(); if (wDoc.CustomXMLParts != null) { foreach (Microsoft.Office.Core.CustomXMLPart xmlPart in wDoc.CustomXMLParts) { if (!xmlPart.BuiltIn) { xmlPartIds.Add(xmlPart.Id); } } } foreach (string xmlPartId in xmlPartIds) { Microsoft.Office.Core.CustomXMLPart oldXmlPart = wDoc.CustomXMLParts.SelectByID(xmlPartId); if (oldXmlPart != null) { oldXmlPart.Delete(); } } if (wDoc.Bookmarks != null) { foreach (Microsoft.Office.Interop.Word.Bookmark wBm in wDoc.Bookmarks) { if (Core.MarkupUtilities.IsProntoDocCommentBookmark(wBm.Name)) { wBm.Range.Text = string.Empty; // remove the bookmark } } } } catch { } }
private static string GetTextFromWord(Word.Application WordApp, string file) { //converts document to string StringBuilder text = new StringBuilder(); object miss = System.Reflection.Missing.Value; object path = file; object readOnly = true; Microsoft.Office.Interop.Word.Document docs = WordApp.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); string WordText = docs.Range().Text; docs.Application.Quit(); return(WordText); }
public void changeTextForContracts(object templateForNewCompanyContract, string[] data) { //now create word file into template and fill data Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); //load document Microsoft.Office.Interop.Word.Document doc = null; object missing = Type.Missing; doc = app.Documents.Open(templateForNewCompanyContract, missing, missing); app.Selection.Find.ClearFormatting(); app.Selection.Find.Replacement.ClearFormatting(); string[] tmpForData = new string[12]; tmpForData = data; app.Selection.Find.Execute("<PlCompanyName>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[0], 2); app.Selection.Find.Execute("<PlCompanyNIP>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[1], 2); app.Selection.Find.Execute("<PlCompanyDIC>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[2], 2); app.Selection.Find.Execute("<PlCompanyRepresentant>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[3], 2); app.Selection.Find.Execute("<newCompanyName>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[4], 2); app.Selection.Find.Execute("<newCompanyAdress>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[5], 2); app.Selection.Find.Execute("<newCompanyIC>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[6], 2); app.Selection.Find.Execute("<newCompanyRepresentant>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[7], 2); app.Selection.Find.Execute("<newCompanyTypeOfWork>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[8], 2); app.Selection.Find.Execute("<newCompanyDate>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[9], 2); app.Selection.Find.Execute("<PlCompanyKRS>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[10], 2); app.Selection.Find.Execute("<newCompanyTypeOfWorkPl>", missing, missing, missing, missing, missing, missing, missing, missing, tmpForData[11], 2); Random rand = new Random(); int ddd; ddd = rand.Next(); object FilePathForContractCz = (object)"Y:\\Legalizace\\Fresh L\\!!!Contracts\\" + tmpForData[1] + "_" + ddd + "Smlouva.docx"; doc.SaveAs2(FilePathForContractCz, missing, missing, missing); MessageBox.Show("Files Are Created!"); doc.Close(false, missing, missing); app.Quit(false, false, false); System.Runtime.InteropServices.Marshal.ReleaseComObject(app); }