static void Main(string[] args) { Microsoft.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); // C# doesn't have optional arguments so we'll need a dummy value object oMissing = System.Reflection.Missing.Value; // Get list of Word files in specified directory DirectoryInfo dirInfo = new DirectoryInfo(@"\\server\folder"); FileInfo[] wordFiles = dirInfo.GetFiles("*.doc"); word.Visible = false; word.ScreenUpdating = false; foreach (FileInfo wordFile in wordFiles) { // Cast as Object for word Open method Object filename = (Object)wordFile.FullName; // Use the dummy value as a placeholder for optional arguments Document doc = word.Documents.Open(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); doc.Activate(); object outputFileName = wordFile.FullName.Replace(".doc", ".pdf"); object fileFormat = WdSaveFormat.wdFormatPDF; // Save document into PDF Format doc.SaveAs(ref outputFileName, ref fileFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); // Close the Word document, but leave the Word application open. // doc has to be cast to type _Document so that it will find the // correct Close method. object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; } // word has to be cast to type _Application so that it will find // the correct Quit method. ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); word = null; }
static void InsertTextOnShtat() { using (shtatDB db = new shtatDB()) { var items = db.shtat49289_.ToList(); // Создаём объект word Microsoft.Office.Interop.Word._Application OneWord = new Microsoft.Office.Interop.Word.Application(); OneWord.WindowState = Word.WdWindowState.wdWindowStateNormal; // Создаем документ var OneDoc = OneWord.Documents.Add(); foreach (var item in items) { OneDoc.Content.InsertAfter($"{item.family} {item.name} {item.surname}, {item.birth}\n"); } // Выходим и закрываем OneDoc.SaveAs2(@"D:\shtat49289.docx"); OneDoc.Close(); OneWord.Quit(); } }
//Methode Find and Replace: private void FindAndReplace(Microsoft.Office.Interop.Word.Application wordApp, object findText, object replaceWithText) { object matchCase = true; object matchWholeWord = true; object matchWildCards = false; object matchSoundLike = false; object nmatchAllForms = false; object forward = true; object format = false; object matchKashida = false; object matchDiactitics = false; object matchAlefHamza = false; object matchControl = false; object read_only = false; object visible = true; object replace = 2; object wrap = 1; wordApp.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildCards, ref matchSoundLike, ref nmatchAllForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace, ref matchKashida, ref matchDiactitics, ref matchAlefHamza, ref matchControl); }
/// <summary> /// Convert the word document to xps document /// </summary> /// <param name="wordFilename">Word document Path</param> /// <param name="xpsFilename">Xps document Path</param> /// <returns></returns> private XpsDocument ConvertWordToXps(string wordFilename, string xpsFilename) { // Create a WordApplication and host word document Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); try { wordApp.Documents.Open(wordFilename); // To Invisible the word document wordApp.Application.Visible = false; // Minimize the opened word document wordApp.WindowState = WdWindowState.wdWindowStateMinimize; Document doc = wordApp.ActiveDocument; doc.SaveAs(xpsFilename, WdSaveFormat.wdFormatXPS); XpsDocument xpsDocument = new XpsDocument(xpsFilename, FileAccess.Read); return(xpsDocument); } catch (Exception ex) { MessageBox.Show("Ошибка: " + ex.ToString()); return(null); } finally { wordApp.Documents.Close(); ((_Application)wordApp).Quit(WdSaveOptions.wdDoNotSaveChanges); } }
static void InsertText() { // Создаём объект word Microsoft.Office.Interop.Word._Application OneWord = new Microsoft.Office.Interop.Word.Application(); OneWord.WindowState = Word.WdWindowState.wdWindowStateNormal; // Создаем документ var OneDoc = OneWord.Documents.Add(); for (int i = 1; i <= 100; i++) { OneDoc.Content.InsertAfter($"tested {i}\n"); if (i % 2 == 0) { OneWord.ActiveDocument.Characters.Last.Select(); OneWord.Selection.Collapse(); OneWord.Selection.InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak); } } // Выходим и закрываем OneDoc.SaveAs2(@"D:\SaveDocFile.docx"); OneDoc.Close(); OneWord.Quit(); }
private void btn_New_Click(object sender, EventArgs e) { btn_New.Enabled = false;//将新建按钮设置为不可用 ThreadPool.QueueUserWorkItem(//开始线程池 (pp) => { object G_missing = System.Reflection.Missing.Value; object G_str_path = System.Reflection.Missing.Value; Word.Application G_wa = new Microsoft.Office.Interop.Word.Application();//创建应用程序对象 object P_obj = "Normal.dot";//定义文档模版 FolderBrowserDialog G_FolderBrowserDialog = new FolderBrowserDialog(); Word.Document P_wd = G_wa.Documents.Add(ref P_obj, ref G_missing, ref G_missing, ref G_missing); G_str_path = string.Format(//计算文件保存路径 @"{0}\{1}",G_FolderBrowserDialog.SelectedPath,DateTime.Now.ToString("yyyy年M月d日h时s秒fff毫秒")+".doc" ); P_wd.SaveAs( ref G_str_path, ref G_missing,ref G_missing,ref G_missing,ref G_missing, ref G_missing,ref G_missing,ref G_missing,ref G_missing, ref G_missing,ref G_missing,ref G_missing,ref G_missing, ref G_missing,ref G_missing,ref G_missing ); ((Word.Application)G_wa.Application).Quit(ref G_missing, ref G_missing, ref G_missing); this.Invoke( (MethodInvoker)(()=> { MessageBox.Show("Word文档已经建立!","提示!"); btn_diplay.Enabled = true; } ) ); }); }
private bool WordToPDF(string inePath, string outputPath) { bool result = false; Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application(); Word.Document document = null; try { application.Visible = false; document = application.Documents.Open(inePath); document.ExportAsFixedFormat(outputPath, Word.WdExportFormat.wdExportFormatPDF); result = true; } catch (Exception e) { Console.WriteLine(e.Message); result = false; } finally { document.Close(); application.Quit(); } return(result); }
static void Main(string[] args) { // Open XML Method object fileName = @"OpenXmlTest.docx"; using (WordprocessingDocument myDocument = WordprocessingDocument.Open(fileName.ToString(), true)) { var textbox = myDocument.MainDocumentPart.Document.Descendants <TextBoxContent>().First(); Console.WriteLine(textbox.InnerText); } // Office Interop Method object missing = System.Reflection.Missing.Value; object readOnly = false; object isVisible = true; Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); wordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing); object firstShape = 1; string textFrameText = wordApp.ActiveDocument.Shapes.get_Item(ref firstShape).TextFrame.TextRange.Text; wordApp.Quit(ref missing, ref missing, ref missing); Console.WriteLine(textFrameText); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); }
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); } }
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> /// Reads a Word document and places the words into a StringBuilder. /// </summary> /// <param name="filePath">The path to the document.</param> /// <returns>Returns a StringBuilder with the content of the document.</returns> public static StringBuilder ReadWordDocument(string filePath) { if (Path.GetExtension(filePath) == ".doc" || Path.GetExtension(filePath) == ".docx") { Microsoft.Office.Interop.Word.Application a = new Microsoft.Office.Interop.Word.Application(); Word.Document doc = a.Documents.Open(filePath); int wordCount = doc.Words.Count; StringBuilder content = new StringBuilder(); for (int i = 1; i <= wordCount; i++) { string text = doc.Words[i].Text; } a.Quit(); return(content); } else { Console.WriteLine(filePath + " does not have a valid Word extension."); return(null); } }
void FindAndReplace(Microsoft.Office.Interop.Word.Application doc, string findText, string replaceWithText) { if (replaceWithText.Length > 255) { FindAndReplace(doc, findText, findText + replaceWithText.Substring(255)); replaceWithText = replaceWithText.Substring(0, 255); } object matchCase = false; object matchWholeWord = true; object matchWildCards = false; object matchSoundsLike = false; object matchAllWordForms = false; object forward = true; object format = false; object matchKashida = false; object matchDiacritics = false; object matchAlefHamza = false; object matchControl = false; object read_only = false; object visible = true; object replace = 2; object wrap = 1; doc.Selection.Find.Execute(findText, ref matchCase, ref matchWholeWord, ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, replaceWithText, ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl); }
//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); }
/// <summary> /// 焦点移动字符数 /// </summary> /// <param name="wordApp">word app</param> /// <param name="count">移动数量</param> public static void MoveCharacter(Microsoft.Office.Interop.Word.Application wordApp, int count) { object _count = count; object wdCharacter = WdUnits.wdCharacter; wordApp.Selection.Move(ref wdCharacter, ref _count); }
public static void Read(string Fileptah) { //byte[] byData=new try { Word.Application app = new Microsoft.Office.Interop.Word.Application(); Word.Document doc = null; object unknow = Type.Missing; app.Visible = false; //如果为true,会打开word文档 string str = Fileptah; object file = str; doc = app.Documents.Open(ref file, ref unknow); string[] temp = new string[doc.Paragraphs.Count]; for (int i = 0; i < doc.Paragraphs.Count; i++) { temp[i] = doc.Paragraphs[i + 1].Range.Text.Trim(); } foreach (string x in temp) { Console.WriteLine(x); } } catch (Exception e) { Console.WriteLine(e.Source); Console.WriteLine(e.Message); } }
/// <summary> /// 焦点移动count段落 /// </summary> /// <param name="wordApp">word app</param> /// <param name="count"></param> public static void MoveParagraph(Microsoft.Office.Interop.Word.Application wordApp, int count) { object _count = count; object wdP = WdUnits.wdParagraph;//换一段落 wordApp.Selection.Move(ref wdP, ref _count); }
/// <summary> /// 焦点移动count行 /// </summary> /// <param name="wordApp">word app</param> /// <param name="count"></param> public static void MoveRow(Microsoft.Office.Interop.Word.Application wordApp, int count) { object _count = count; object WdLine = WdUnits.wdLine;//换一行 wordApp.Selection.Move(ref WdLine, ref _count); }
private void ProcessHeaderFooter(Microsoft.Office.Interop.Word.Application wApp, Microsoft.Office.Interop.Word.Document wDoc) { // copy header wApp.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView; wApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader; Microsoft.Office.Interop.Word.Range wHeaderRange = wApp.Selection.HeaderFooter.Range; ProcessBookmarks(wHeaderRange.Bookmarks, wDoc); wHeaderRange.CopyAsPicture(); // paste header wApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; wApp.Selection.HomeKey(Microsoft.Office.Interop.Word.WdUnits.wdStory); Microsoft.Office.Interop.Word.Paragraph wHeader = wDoc.Content.Paragraphs.Add(); wApp.Selection.PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdPasteDefault); // copy footer wApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter; Microsoft.Office.Interop.Word.Range wFooterRange = wApp.Selection.HeaderFooter.Range; ProcessBookmarks(wFooterRange.Bookmarks, wDoc); wFooterRange.CopyAsPicture(); // paste footer wApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; wApp.Selection.EndKey(Microsoft.Office.Interop.Word.WdUnits.wdStory); Microsoft.Office.Interop.Word.Paragraph wFooter = wDoc.Content.Paragraphs.Add(); wApp.Selection.PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdPasteDefault); }
private string SaveAsHtmlForPdm(string filePath, Core.InternalBookmarkDomain firstDomain) { string tempCopyFileName = Path.ChangeExtension(Path.GetTempFileName(), FileExtension.Docx); string tempHtmlName = Path.ChangeExtension(Path.GetTempFileName(), FileExtension.Html); Word.Application word = null; Word.Document newDoc = null; File.Copy(filePath, tempCopyFileName, true); try { word = new Microsoft.Office.Interop.Word.Application(); word.DefaultWebOptions().Encoding = MsoEncoding.msoEncodingUTF8; newDoc = word.Documents.Open(tempCopyFileName, Visible: false, AddToRecentFiles: false, Encoding: MsoEncoding.msoEncodingUTF8); RemoveCustomXmlParts(newDoc); MakePdwWatermark(word, TemplateType.Pdm, firstDomain); newDoc.SaveAs(tempHtmlName, Word.WdSaveFormat.wdFormatFilteredHTML, AddToRecentFiles: false, Encoding: MsoEncoding.msoEncodingUTF8); ((Word._Document)newDoc).Close(); } finally { ((Word._Application)word).Quit(Type.Missing, Type.Missing, Type.Missing); System.Runtime.InteropServices.Marshal.ReleaseComObject(word); System.Runtime.InteropServices.Marshal.ReleaseComObject(newDoc); File.Delete(tempCopyFileName); } return(tempHtmlName); }
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); }
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(); } //нет ссылок
}// 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); }
//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 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> /// 转换word 成PDF文档 /// </summary> /// <param name="_lstrInputFile">原文件路径</param> /// <param name="_lstrOutFile">pdf文件输出路径</param> /// <returns>true 成功</returns> public static bool ConvertWordToPdf(string _lstrInputFile, string _lstrOutFile) { Microsoft.Office.Interop.Word.Application application = null; Word.Document document = null; try { application = new Microsoft.Office.Interop.Word.Application(); application.Visible = false; document = application.Documents.Open(_lstrInputFile); document.ExportAsFixedFormat(_lstrOutFile, Word.WdExportFormat.wdExportFormatPDF); return(true); } catch (Exception ex) { return(false); } finally { if (document != null) { document.Close(); } if (application != null) { application.Quit(); } } }
private void btn_hrm_res_resignation_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); OpenFileDialog open = new OpenFileDialog(); if (open.ShowDialog() == DialogResult.OK) { object fileName = open.FileName; object readOnly = true; object isVisible = true; object missing = System.Reflection.Missing.Value; wordApp.Visible = true; Word.Document newDoc = wordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible); newDoc.Activate(); this.FindAndReplace(wordApp, "<name>", txt_flname.Text); this.FindAndReplace(wordApp, "<address>", lbl_fullAdd.Text); this.FindAndReplace(wordApp, "<join_date>", txt_joinDate.Text); this.FindAndReplace(wordApp, "<position>", txt_position.Text); this.FindAndReplace(wordApp, "<date>", DateTime.Now.ToShortDateString()); } }
//-http://code.msdn.microsoft.com/office/CSVSTOViewWordInWPF-db347436 private XpsDocument ConvertWordToXps(string wordFilename, string xpsFilename) { Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); try { wordApp.Documents.Open(wordFilename); wordApp.Application.Visible = false; wordApp.WindowState = WdWindowState.wdWindowStateMinimize; Document doc = wordApp.ActiveDocument; doc.SaveAs(xpsFilename, WdSaveFormat.wdFormatXPS); XpsDocument xpsDocument = new XpsDocument(xpsFilename, FileAccess.Read); return(xpsDocument); } catch (Exception ex) { return(null); } finally { wordApp.Documents.Close(); ((_Application)wordApp).Quit(WdSaveOptions.wdDoNotSaveChanges); } }
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() + "秒!"); }
public void processWord(string saved_path, bool newSmry) { word_app = createWordApp(); this.insertBookmark(saved_doc_list); object strFileName = saved_path; Object Nothing = System.Reflection.Missing.Value; object readOnly = false; object isVisible = false; word_wrt = word_app.Documents.Open(ref strFileName, ref Nothing, ref readOnly, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref isVisible, ref Nothing, ref Nothing, ref Nothing, ref Nothing); word_wrt.Activate(); //word_wrt.Paragraphs.Last.Range.Text = "test text" + "\n";//加个结束符(增加一段),否则再次插入的时候就成了替换. this.writeSammary(); //保存 word_wrt.Save(); // test code this.buildTOC(saved_path, newSmry); // test code try { word_show.Quit(ref Nothing, ref Nothing, ref Nothing); word_app.Quit(ref Nothing, ref Nothing, ref Nothing); } catch (Exception) { } word_app = null; word_show = null; }
} //нет ссылок 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
public static XpsDocument ConvertWordToXps(string wordFilename, string xpsFilename) { // Create a WordApplication and host word document Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); try { wordApp.Documents.Open(wordFilename); // To Invisible the word document wordApp.Application.Visible = false; // Minimize the opened word document wordApp.WindowState = WdWindowState.wdWindowStateMinimize; Document doc = wordApp.ActiveDocument; doc.SaveAs(xpsFilename, WdSaveFormat.wdFormatXPS); XpsDocument xpsDocument = new XpsDocument(xpsFilename, FileAccess.Read); return xpsDocument; } catch (Exception ex) { MessageBox.Show("Error occurs, The error message is " + ex.ToString()); return null; } finally { wordApp.Documents.Close(); ((_Application)wordApp).Quit(WdSaveOptions.wdDoNotSaveChanges); } }
public static void Word2Format(object G_FilePath, object P_str_path, Word.WdSaveFormat wdf) { Word.Application G_wa; //定义Word应用程序字段 object G_missing = System.Reflection.Missing.Value; //定义G_missing字段并添加引用 //创建应用程序对象 G_wa = new Microsoft.Office.Interop.Word.Application(); G_wa.Visible = false; //打开Word文档 Word.Document P_wd = G_wa.Documents.Open( ref G_FilePath, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing); object P_Format = wdf;//创建保存文档参数 //保存Word文件 try { P_wd.SaveAs( ref P_str_path, ref P_Format, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing, ref G_missing); } catch { } ((Word._Application)G_wa.Application).Quit(//退出应用程序 ref G_missing, ref G_missing, ref G_missing); }
public static void ConvertFromWord(string sourcePath, string targetPath) { Word.Application application = null; Word.Document document = null; try { application = new Microsoft.Office.Interop.Word.Application(); application.Application.Visible = false; document = application.Documents.Open(sourcePath); document.SaveAs(targetPath, Word.WdSaveFormat.wdFormatPDF); } finally { if (document != null) { ((Word._Document)document).Close(); document = null; } if (application != null) { ((Word._Application)application).Quit(Word.WdSaveOptions.wdDoNotSaveChanges); application = null; } } }
public static Word.Application createWordShow() { if (word_show == null) { word_show = new Word.Application(); } return word_show; }
public static Word.Application createWordApp() { if (word_app == null) { word_app = new Word.Application(); } return word_app; }
public ResultType_enum Learn(string docPath, out int productAddedCount, out int productRepeatCount, out int productMergeCount, out string message) { productAddedCount = 0; productRepeatCount = 0; productMergeCount = 0; try { isWork = true; message = ""; // Проверка пути документа if (!File.Exists(docPath)) { message = "Документа по пути <" + docPath + "> не существует"; return ResultType_enum.Error; } //Создаём новый Word.Application Word.Application application = new Microsoft.Office.Interop.Word.Application(); //Загружаем документ Microsoft.Office.Interop.Word.Document doc = null; object fileName = docPath; object falseValue = false; object trueValue = true; object missing = Type.Missing; doc = application.Documents.Open(ref fileName, ref missing, ref trueValue, 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); // Ищем таблицу с данными Microsoft.Office.Interop.Word.Table tbl = null; try { tbl = application.ActiveDocument.Tables[1]; } catch { message = "В документе не найдена таблица для обучения"; return ResultType_enum.Error; } if (tbl == null) { message = "В документе не найдена таблица для обучения"; return ResultType_enum.Error; } if (tbl.Columns.Count != 8) { message = "Количество столбцов таблицы не совпадает со спецификацией"; return ResultType_enum.Error; } // Заполняем продукты Product product = null; Property property = null; bool isNewProduct = false; string productName = ""; var r = mvm.dc.Rubrics.FirstOrDefault(m => m.Name.ToLower() == "--без рубрики--"); var t = mvm.dc.Templates.FirstOrDefault(m => m.Name.ToLower() == "форма 2"); for (int i = 4; i <= tbl.Rows.Count; i++) { // Название продукта try { /*tbl.Cell(i, 2).Select(); Word.Selection sel = application.Selection; bool sss = sel.IsEndOfRowMark; int ss = sel.Rows.Count;*/ //sel.MoveDown(); Word.Cell ddd = tbl.Cell(i, 2).Next; if ((Globals.CleanWordCell(tbl.Cell(i, 2).Range.Text.Trim()) == productName) || (Globals.CleanWordCell(tbl.Cell(i, 2).Range.Text.Trim()) == "")) { isNewProduct = false; } else { isNewProduct = true; productName = Globals.CleanWordCell(tbl.Cell(i, 2).Range.Text.Trim()); } } catch (Exception ex) { isNewProduct = false; } if (isNewProduct) { if (!isWork) break; product = new Product(); product.Name = productName; try { product.TradeMark = Globals.CleanWordCell(tbl.Cell(i, 3).Range.Text.Trim()); } catch { product.TradeMark = ""; } // Проверить на повтор Product repeatProduct = mvm.dc.Products.FirstOrDefault(m => (m.Name == product.Name && m.TradeMark == product.TradeMark)); if (repeatProduct != null) { if (repeatProduct.Templates.FirstOrDefault(m => m.Name.Trim().ToLower() == "форма 2") == null) { product = repeatProduct; } else { productRepeatCount++; continue; } } else { product.Rubric = r; mvm.dc.Products.Add(product); t.Products.Add(product); productAddedCount++; mvm.dc.SaveChanges(); try { Application.Current.Dispatcher.BeginInvoke(new Action(() => { mvm.ProductCollection.Add(product); })); } catch { } } product.Templates.Add(mvm.dc.Templates.FirstOrDefault(m => m.Name.ToLower() == "форма 2")); try { Application.Current.Dispatcher.BeginInvoke(new Action(() => { mvm.TemplateCollection.FirstOrDefault(m => m.Name.ToLower() == "форма 2").Products.Add(product); })); } catch { } //mvm.TemplateCollection = new ObservableCollection<Template>(mvm.dc.Templates); } // Добавляем свойство property = new Property(); product.Properties.Add(property); try { // Требуемый параметр ParamValue pv = new ParamValue(); property.ParamValues.Add(pv); pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Требуемый параметр" && m.Template.Name.ToLower() == "форма 2"); pv.Property = property; pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 4).Range.Text.Trim())); // Требуемое значение pv = new ParamValue(); property.ParamValues.Add(pv); pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Требуемое значение" && m.Template.Name.ToLower() == "форма 2"); pv.Property = property; pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 5).Range.Text.Trim())); // Значение, предлагаемое участником pv = new ParamValue(); property.ParamValues.Add(pv); pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Значение, предлагаемое участником" && m.Template.Name.ToLower() == "форма 2"); pv.Property = property; try { pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 6).Range.Text.Trim())); } catch { pv.Value = ""; } // Единица измерения pv = new ParamValue(); property.ParamValues.Add(pv); pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Единица измерения" && m.Template.Name.ToLower() == "форма 2"); pv.Property = property; pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 7).Range.Text.Trim())); // Сертификация pv = new ParamValue(); property.ParamValues.Add(pv); pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Сертификация" && m.Template.Name.ToLower() == "форма 2"); pv.Property = property; try { pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 8).Range.Text.Trim())); } catch { pv.Value = ""; } } catch (Exception ex) { string sss = ""; } } // Закрываем приложение application.Quit(ref missing, ref missing, ref missing); application = null; return ResultType_enum.Done; // Заносим продукты в БД //return dbEngineDocs.SetProducts(DocTemplate.Template_2, products, out productAddedCount, out productRepeatCount, out message); } catch (Exception ex) { message = ex.Message + '\n' + ex.StackTrace; return ResultType_enum.Error; } finally { isWork = false; } }
public ResultType_enum Learn(string docPath, out int productAddedCount, out int productRepeatCount, out int productMergeCount, out string message) { productAddedCount = 0; productRepeatCount = 0; productMergeCount = 0; try { isWork = true; message = ""; // Проверка пути документа if (!File.Exists(docPath)) { message = "Документа по пути <" + docPath + "> не существует"; return ResultType_enum.Error; } //Создаём новый Word.Application Word.Application application = new Microsoft.Office.Interop.Word.Application(); //Загружаем документ Microsoft.Office.Interop.Word.Document doc = null; object fileName = docPath; object falseValue = false; object trueValue = true; object missing = Type.Missing; doc = application.Documents.Open(ref fileName, ref missing, ref trueValue, 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); // Ищем таблицу с данными Microsoft.Office.Interop.Word.Table tbl = null; try { tbl = application.ActiveDocument.Tables[1]; } catch { message = "В документе не найдена таблица для обучения"; return ResultType_enum.Error; } if (tbl == null) { message = "В документе не найдена таблица для обучения"; return ResultType_enum.Error; } if (tbl.Columns.Count != 6) { message = "Количество столбцов таблицы не совпадает со спецификацией"; return ResultType_enum.Error; } //DocumentDbContext dc = new DocumentDbContext(); // Заполняем продукты var r = mvm.dc.Rubrics.FirstOrDefault(m => m.Name.ToLower() == "--без рубрики--"); var t = mvm.dc.Templates.FirstOrDefault(m => m.Name.ToLower() == "свобода"); // Новый обход документа Product product = null; Property property = null; Word.Cell cell = tbl.Cell(4, 1); while (cell != null) { try { string cellValue = cell.Range.Text.Trim(); switch (cell.ColumnIndex) { case (2): // Название (--ПЕРВОЕ ЗНАЧЕНИЕ--) product = new Product(); product.Name = Globals.DeleteNandSpaces(Globals.ConvertTextExtent(Globals.CleanWordCell(cellValue))); property = new Property(); break; case (5): // Торговая марка if (product == null) break; product.TradeMark = Globals.DeleteNandSpaces(Globals.ConvertTextExtent(Globals.CleanWordCell(cellValue))); break; case (3): // Требования заказчика ParamValue pv = new ParamValue(); property.ParamValues.Add(pv); pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Требования заказчика" && m.Template.Name.ToLower() == "свобода"); pv.Property = property; pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(cellValue)); break; case (4): // Требования участника pv = new ParamValue(); property.ParamValues.Add(pv); pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Требования участника" && m.Template.Name.ToLower() == "свобода"); pv.Property = property; pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(cellValue)); break; case (6): // Сертификация (--ПОСЛЕДНЕЕ ЗНАЧЕНИЕ--) pv = new ParamValue(); property.ParamValues.Add(pv); pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Сертификация" && m.Template.Name.ToLower() == "свобода"); pv.Property = property; pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(cellValue)); // Добавляем к продукту значения, шаблон, рубрику if ((property.ParamValues.ElementAt(0).Value != "") && ((property.ParamValues.ElementAt(1).Value != "")) && ((property.ParamValues.ElementAt(2).Value != ""))) { product.Properties.Add(property); } // Проверка на повтор // Если совпали название и товарный знак и значения по всем атрибутам, то это ПОВТОР // Если совпали название и товарный знак и значений по данному шаблону нет (или пусты), то это СЛИЯНИЕ // Если совпали название и товарный знак и значения НЕ совпали, то это НОВЫЙ ПРОДУКТ IEnumerable<Product> repeatProducts = mvm.dc.Products.Where(m => (m.Name == product.Name && m.TradeMark == product.TradeMark)); if (repeatProducts.Count() > 0) { // Изначально проверим на повтор foreach (Product repeatProduct in repeatProducts) { // Шаблон var repeatTemplate = product.Templates.FirstOrDefault(m => m.Name.Trim().ToLower() == "свобода"); if (repeatTemplate == null) continue; // Свойства продукта по шаблону IEnumerable<Property> repeatProperties = product.Properties.SelectMany(m => m.ParamValues.Where(p => repeatTemplate.Param.Contains(p.Param))).Select(f => f.Property).Distinct(); if (repeatProperties.Count() != 3) continue; foreach (Property repeatProperty in repeatProperties) { } } if (repeatProducts.Count() > 1) { } } /*if (repeatProduct != null) { if (repeatProduct.Templates.FirstOrDefault(m => m.Name.Trim().ToLower() == "свобода") == null) { product = repeatProduct; } else { productRepeatCount++; continue; } }*/ product.Rubric = r; mvm.dc.Products.Add(product); productAddedCount++; t.Products.Add(product); mvm.dc.SaveChanges(); Application.Current.Dispatcher.BeginInvoke(new Action(() => { mvm.TemplateCollection.FirstOrDefault(m => m.Name.ToLower() == "свобода").Products.Add(product); })); Application.Current.Dispatcher.BeginInvoke(new Action(() => { mvm.ProductCollection.Add(product); })); break; default: break; } } catch (Exception ex) { break; } finally { cell = cell.Next; } } /*for (int i = 4; i <= tbl.Rows.Count; i++) { if (!isWork) break; Product product = new Product(); // Название продукта product.Name = Globals.DeleteNandSpaces(Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 2).Range.Text.Trim()))); product.TradeMark = Globals.DeleteNandSpaces(Globals.CleanWordCell(tbl.Cell(i, 5).Range.Text.Trim())); if (product.Name == "") continue; // Проверить на повтор Product repeatProduct = mvm.dc.Products.FirstOrDefault(m => (m.Name == product.Name && m.TradeMark == product.TradeMark)); if (repeatProduct != null) { if (repeatProduct.Templates.FirstOrDefault(m => m.Name.Trim().ToLower() == "свобода") == null) { product = repeatProduct; } else { productRepeatCount++; continue; } } // Проверка заполнения атрибутов строки if ((Globals.CleanWordCell(tbl.Cell(i, 3).Range.Text.Trim()) == "") && (Globals.CleanWordCell(tbl.Cell(i, 4).Range.Text.Trim()) == "") && (Globals.CleanWordCell(tbl.Cell(i, 6).Range.Text.Trim())) == "") { continue; } // У данного шаблона одно свойство Property property = new Property(); try { // Требования заказчика ParamValue pv = new ParamValue(); property.ParamValues.Add(pv); pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Требования заказчика" && m.Template.Name.ToLower() == "свобода"); pv.Property = property; pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 3).Range.Text.Trim())); // Требования участника pv = new ParamValue(); property.ParamValues.Add(pv); pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Требования участника" && m.Template.Name.ToLower() == "свобода"); pv.Property = property; pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 4).Range.Text.Trim())); // Сертификация pv = new ParamValue(); property.ParamValues.Add(pv); pv.Param = mvm.dc.Params.FirstOrDefault(m => m.Name == "Сертификация" && m.Template.Name.ToLower() == "свобода"); pv.Property = property; pv.Value = Globals.ConvertTextExtent(Globals.CleanWordCell(tbl.Cell(i, 6).Range.Text.Trim())); // Добавляем к продукту значения, шаблон, рубрику product.Properties.Add(property); } catch { string sss = ""; continue; } product.Rubric = r; mvm.dc.Products.Add(product); productAddedCount++; t.Products.Add(product); mvm.dc.SaveChanges(); try { Application.Current.Dispatcher.BeginInvoke(new Action(() => { mvm.TemplateCollection.FirstOrDefault(m => m.Name.ToLower() == "свобода").Products.Add(product); })); } catch { } try { Application.Current.Dispatcher.BeginInvoke(new Action(() => { mvm.ProductCollection.Add(product); })); } catch { } }*/ // Закрываем приложение application.Quit(ref missing, ref missing, ref missing); application = null; return ResultType_enum.Done; } catch (Exception ex) { message = ex.Message + '\n' + ex.StackTrace; return ResultType_enum.Error; } finally { isWork = false; } }
/// <summary> /// Чтение текста из файла /// </summary> /// <param name="str"> подается на вход. Адрес папки с файлами. </param> /// <returns> Возвращает весь текст из документа в перемнной типа string </returns> public static string Read(ref string str) { Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); object miss = System.Reflection.Missing.Value; Console.WriteLine("Input name of file. Example: Text.docx or Text.doc"); string nameFile = Console.ReadLine(); string copyName = nameFile; //Если файл имеет неверное расширение, т.е. это не Word-овский файл, то выведется сообщение об ошибке. if (copyName.EndsWith(".docx") || copyName.EndsWith(".doc")) { string adresse = str + nameFile; object path = @adresse; object readOnly = true; //Проверка на правильность указания адреса файла try { 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 totaltext = ""; for (int i = 0; i < docs.Paragraphs.Count; i++) totaltext += docs.Paragraphs[i + 1].Range.Text.ToString(); docs.Close(); word.Quit(); return totaltext; } catch (Exception e) { Console.WriteLine("Error! File not find!"); Console.ReadKey(); return ""; } } else { Console.WriteLine("Error!!! Invalid file extension!"); Console.ReadKey(); return ""; } }
private void PerformBuildRequirements() { _excel = new Excel.Application(); _word = new Word.Application(); _word.Visible = true; _excel.Visible = true; this.BeginInvoke( new Action<Form1>(s => { btnBuild.Enabled = false; btnBuild.Text = "Working"; }), new object[] { this }); var spreadsheetPath = tbSpreadsheetPath.Text; if (File.Exists(spreadsheetPath)) { var workbook = _excel.Workbooks.Open(spreadsheetPath); var requirements = new List<Requirement>(); Word.Document doc = BuildRequirementsDoc(workbook, out requirements); if (cbBuildTrace.Enabled) { BuildTraceMatrix(workbook, requirements); try { workbook.Save(); } catch (Exception) { } } try { // This call throws when the user elects to 'cancel' the save operation. doc.Save(); } catch (Exception) { } } else { MessageBox.Show("No spreadsheet selected."); } foreach (Excel.Workbook wb in _excel.Workbooks) { wb.Close(); } _excel.Quit(); _word.Quit(ref Missing, ref Missing, ref Missing); this.BeginInvoke( new Action<Form1>(s => { btnBuild.Enabled = true; btnBuild.Text = "Build"; }), new object[] { this }); }
public string getActiveDocName() { try { word_show = createWordShow(); } catch(Exception) { word_show = null; word_show = createWordShow(); } return word_show.ActiveWindow.Document.Name; //return word_app.ActiveDocument.Name; }
public bool GetOficioContradiccion() { bool isComplete = false; string rutaBase = @"C:\Seguimiento\"; string machote = rutaBase + "Machote.docx"; string nuevoDoc = rutaBase + newFileName; try { // Just to kill WINWORD.EXE if it is running // copy letter format to temp.doc File.Copy(machote, nuevoDoc, true); // create missing object object missing = Missing.Value; // create Word application object Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); // create Word document object Word.Document aDoc = null; // create & define filename object with temp.doc object filename = nuevoDoc; // if temp.doc available if (File.Exists((string)filename)) { object readOnly = false; object isVisible = false; // make visible Word application wordApp.Visible = false; // open Word document named temp.doc aDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing); aDoc.Activate(); Microsoft.Office.Interop.Word.Paragraph oPara1; oPara1 = aDoc.Content.Paragraphs.Add(ref oMissing); //oPara1.Range.ParagraphFormat.Space1; oPara1.Range.Text = "OFICIO " + contradiccion.OficioPlenos; oPara1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; oPara1.Range.Font.Size = 12; oPara1.Range.Font.Name = "Arial"; oPara1.Format.SpaceAfter = 0; //24 pt spacing after paragraph. oPara1.Range.InsertParagraphAfter(); oPara1.Range.Text = "Ciudad de México, " + DateTimeUtilities.ToLongDateFormat(contradiccion.FEnvioOfPlenos); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; oPara1.Range.Text = oficio.Parrafo1; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphJustify; oPara1.Range.Text = oficio.Parrafo2; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.Text = oficio.Parrafo3; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); //oPara1.Range.ParagraphFormat.FirstLineIndent = 40; oPara1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oPara1.Range.ParagraphFormat.FirstLineIndent = 0; oPara1.Range.Text = oficio.Firma; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphJustify; oPara1.Range.Font.Size = 10; oPara1.Range.Text = "C.c.p. Lic. Rafael Coello Cetina.- Secretario General de Acuerdos de la " + "Suprema Corte de Justicia de la Nación.- Para su conocimiento."; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); FindAndReplace(wordApp, "<Encargado>", contradiccion.Titulo + " " + contradiccion.EncargadoStr); FindAndReplace(wordApp, "Distinguido Lic.", "Distinguido Licenciado"); FindAndReplace(wordApp, "<Pleno>", contradiccion.PlenoStr); if (contradiccion.FechaOficioAdmin != null && contradiccion.FechaCorreo != null) { if (contradiccion.FechaOficioAdmin < contradiccion.FechaCorreo) { FindAndReplace(wordApp, "<oficiocorreo>", "oficio"); FindAndReplace(wordApp, "<FechaPrimera>", DateTimeUtilities.ToLongDateFormat(contradiccion.FechaOficioAdmin)); } else { FindAndReplace(wordApp, "<oficiocorreo>", "correo electrónico"); FindAndReplace(wordApp, "<FechaPrimera>", DateTimeUtilities.ToLongDateFormat(contradiccion.FechaCorreo)); } } else if (contradiccion.FechaOficioAdmin != null) { FindAndReplace(wordApp, "<oficiocorreo>", "oficio"); FindAndReplace(wordApp, "<FechaPrimera>", DateTimeUtilities.ToLongDateFormat(contradiccion.FechaOficioAdmin)); } else if (contradiccion.FechaCorreo != null) { FindAndReplace(wordApp, "<oficiocorreo>", "correo electrónico"); FindAndReplace(wordApp, "<FechaPrimera>", DateTimeUtilities.ToLongDateFormat(contradiccion.FechaCorreo)); } FindAndReplace(wordApp, "<NumAsunto>", contradiccion.NumAsunto + "/" + contradiccion.AnioAsunto); FindAndReplace(wordApp, "<RespuestaSga>", contradiccion.OficioRespuestaSga); FindAndReplace(wordApp, "<FRespuestaSga>", DateTimeUtilities.ToLongDateFormat(contradiccion.FRespuestaSga)); FindAndReplace(wordApp, "<Tema>", contradiccion.Tema); aDoc.Save(); aDoc.Close(); wordApp = null; } isComplete = true; contradiccion.OfEnviadoSgaFilePath = nuevoDoc; } catch (Exception ex) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; ErrorUtilities.SetNewErrorMessage(ex, methodName + " Exception,GeneraOficio", "OficiosPleno"); } return isComplete; }
public bool GetOficioSga() { bool isComplete = false; string rutaBase = @"C:\Seguimiento\"; string machote = rutaBase + "Machote.docx"; string nuevoDoc = rutaBase + newFileName; try { // Just to kill WINWORD.EXE if it is running // copy letter format to temp.doc File.Copy(machote, nuevoDoc, true); // create missing object object missing = Missing.Value; // create Word application object Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); // create Word document object Word.Document aDoc = null; // create & define filename object with temp.doc object filename = nuevoDoc; // if temp.doc available if (File.Exists((string)filename)) { object readOnly = false; object isVisible = false; // make visible Word application wordApp.Visible = false; // open Word document named temp.doc aDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing); aDoc.Activate(); Microsoft.Office.Interop.Word.Paragraph oPara1; oPara1 = aDoc.Content.Paragraphs.Add(ref oMissing); //oPara1.Range.ParagraphFormat.Space1; oPara1.Range.Text = "OFICIO " + contradiccion.OficioAdmision; oPara1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; oPara1.Range.Font.Size = 12; oPara1.Range.Font.Name = "Arial"; oPara1.Format.SpaceAfter = 0; //24 pt spacing after paragraph. oPara1.Range.InsertParagraphAfter(); oPara1.Range.Text = "Ciudad de México, " + DateTimeUtilities.ToLongDateFormat(contradiccion.FEnvioOfSga); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; oPara1.Range.Text = oficio.Parrafo1; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.Text = "Distinguido Licenciado Rafael Coello Cetina"; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphJustify; oPara1.Range.Text = oficio.Parrafo2; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.ParagraphFormat.FirstLineIndent = 40; oPara1.Range.Text = oficio.Parrafo3; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.Text = oficio.Parrafo4; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.Text = oficio.Parrafo5; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oPara1.Range.ParagraphFormat.FirstLineIndent = 0; oPara1.Range.Text = oficio.Firma; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); oPara1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphJustify; oPara1.Range.Font.Size = 10; oPara1.Range.Text = "C.c.p. " + contradiccion.EncargadoStr + ".- Secretario de Acuerdos del " + "<Pleno>.- Para su conocimiento y en seguimiento a su oficio " + contradiccion.OficioAdmision + ", recibido el " + DateTimeUtilities.ToLongDateFormat(contradiccion.FechaOficioAdmin) + " del año en curso (contradicción de tesis " + contradiccion.NumAsunto + "/" + contradiccion.AnioAsunto + ")."; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); FindAndReplace(wordApp, "<Tema>", contradiccion.Tema); FindAndReplace(wordApp, "<Pleno>", contradiccion.PlenoStr); FindAndReplace(wordApp, "<NumAsunto>", contradiccion.NumAsunto + "/" + contradiccion.AnioAsunto); if (contradiccion.FechaOficioAdmin == contradiccion.FEnvioOfSga) FindAndReplace(wordApp, "<InicioTermino>", "dia de hoy"); else FindAndReplace(wordApp, "<InicioTermino>", DateTimeUtilities.ToLongDateFormat(contradiccion.FechaOficioAdmin).Replace("de 2016", "").ToLower() + "del año en curso"); aDoc.Save(); aDoc.Close(); // wordApp.Documents.Close(); wordApp = null; } // else // MessageBox.Show("File does not exist.", //"No File", MessageBoxButtons.OK, //MessageBoxIcon.Information); // killprocess("winword"); isComplete = true; contradiccion.OfEnviadoSgaFilePath = nuevoDoc; } catch (Exception ex) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; ErrorUtilities.SetNewErrorMessage(ex, methodName + " Exception,GeneraOficio", "OficiosPleno"); } return isComplete; }
//-http://code.msdn.microsoft.com/office/CSVSTOViewWordInWPF-db347436 private XpsDocument ConvertWordToXps(string wordFilename, string xpsFilename) { Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); try { wordApp.Documents.Open(wordFilename); wordApp.Application.Visible = false; wordApp.WindowState = WdWindowState.wdWindowStateMinimize; Document doc = wordApp.ActiveDocument; doc.SaveAs(xpsFilename, WdSaveFormat.wdFormatXPS); XpsDocument xpsDocument = new XpsDocument(xpsFilename, FileAccess.Read); return xpsDocument; } catch (Exception ex) { return null; } finally { wordApp.Documents.Close(); ((_Application)wordApp).Quit(WdSaveOptions.wdDoNotSaveChanges); } }
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); } }
public void createWord(string saved_path, bool newSmry) { word_app = createWordApp(); this.insertBookmark(saved_doc_list); object strFileName = saved_path; //MessageBox.Show(strFileName.ToString()); if (System.IO.File.Exists((string)strFileName)) System.IO.File.Delete((string)strFileName); Object Nothing = System.Reflection.Missing.Value; word_wrt = word_app.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); object oStyleName = Word.WdBuiltinStyle.wdStyleBodyText; //"Heading 1"; word_wrt.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; word_wrt.Paragraphs.Last.Range.set_Style(ref oStyleName); string strContent = "Schlüsselwörter \r"; word_wrt.Paragraphs.Last.Range.Font.Size = 14; word_wrt.Paragraphs.Last.Range.Font.Bold = 1; word_wrt.Paragraphs.Last.Range.Text = strContent; this.writeSammary(); //将WordDoc文档对象的内容保存为DOC文档 word_wrt.SaveAs(ref strFileName, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); //关闭WordDoc文档对象 word_wrt.Close(ref Nothing, ref Nothing, ref Nothing); //Test code ## this.buildTOC(saved_path, newSmry); //Test code ## try { word_show.Quit(ref Nothing, ref Nothing, ref Nothing); word_app.Quit(ref Nothing, ref Nothing, ref Nothing); } catch(Exception) { } word_app = null; word_show = null; }
public void processWord(string saved_path, bool newSmry) { word_app = createWordApp(); this.insertBookmark(saved_doc_list); object strFileName = saved_path; Object Nothing = System.Reflection.Missing.Value; object readOnly = false; object isVisible = false; word_wrt = word_app.Documents.Open(ref strFileName, ref Nothing, ref readOnly, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref isVisible, ref Nothing, ref Nothing, ref Nothing, ref Nothing); word_wrt.Activate(); //word_wrt.Paragraphs.Last.Range.Text = "test text" + "\n";//加个结束符(增加一段),否则再次插入的时候就成了替换. this.writeSammary(); //保存 word_wrt.Save(); // test code this.buildTOC(saved_path, newSmry); // test code try { word_show.Quit(ref Nothing, ref Nothing, ref Nothing); word_app.Quit(ref Nothing, ref Nothing, ref Nothing); } catch (Exception) { } word_app = null; word_show = null; }
public void buildTOC(string string_File_Name, bool newSmry) { //TODO: try if process old TOC or build new TOC word_app = createWordApp(); object str_File_Name = string_File_Name; //this.created_folder + "\\" + "summary.docx"; Object Nothing = System.Reflection.Missing.Value; Word.Document word_toc = word_app.Documents.Open(ref str_File_Name, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); if (newSmry) { Object oTrue = true; //SETTING THE OUTLINE LEVEL //SELECT THE CONTENTS WHOSE OUTLINE LEVEL NEEDS TO BE CHANGED AND //SET THE VALUE word_app.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel2; word_app.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevel3; word_app.Selection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevelBodyText; // NAME OF THE BOOKMARK IN THE DOCUMENT (.dot Template) WHERE TABLE OF // CONTENTS NEEDS TO BE ADDED Word.Selection toc_pos = word_app.ActiveWindow.Selection; toc_pos.Start = 16; toc_pos.End = 16; Word.Range rngTOC = toc_pos.Range; // SELECTING THE SET RANGE rngTOC.Select(); // INCLUDING THE TABLE OF CONTENTS Object oUpperHeadingLevel = "1"; Object oLowerHeadingLevel = "3"; Object oTOCTableID = "TableOfContents"; word_toc.TablesOfContents.Add(rngTOC, ref oTrue, ref oUpperHeadingLevel, ref oLowerHeadingLevel, ref Nothing, ref oTOCTableID, ref oTrue, ref oTrue, ref Nothing, ref oTrue, ref oTrue, ref oTrue); } else { word_toc.TablesOfContents[1].Update(); } word_toc.Save(); }
public void openWordFile(string str_File_Name) { word_show = createWordShow(); object file_Name = str_File_Name; Object Nothing = System.Reflection.Missing.Value; try { Word.Document word_op = word_show.Documents.Open(ref file_Name, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); } catch (Exception) { try { //word_show.Quit(); word_show = null; word_show = System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application") as Word.Application; Word.Document word_op = word_show.Documents.Open(ref file_Name, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); } catch(Exception) { //word_show.Quit(); word_show = null; createWordShow(); Word.Document word_op = word_show.Documents.Open(ref file_Name, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); } } word_show.Visible = true; }