/// <summary>
    /// WORD EVENT  fires before a save event.
    /// </summary>
    /// <param name="Doc"></param>
    /// <param name="SaveAsUI"></param>
    /// <param name="Cancel"></param>
    void oWord_DocumentBeforeSave(Word.Document Doc, ref bool SaveAsUI, ref bool Cancel)
    {
        // This could mean one of four things:
        // 1) we have the user clicking the save button
        // 2) Another add-in or process firing a resular Document.Save()
        // 3) A Save As from the user so the dialog came up
        // 4) Or an Auto-Save event
        // so, we will start off by first:
        // 1) Grabbing the current background save flag. We want to force
        //    the save into the background so that Word will behave
        //    asyncronously. Typically, this feature is on by default,
        //    but we do not want to make any assumptions or this code
        //    will fail.
        // 2) Next, we fire off a thread that will keep checking the
        //    BackgroundSaveStatus of Word. And when that flag is OFF
        //    no know we are AFTER the save event
        preserveBackgroundSave       = oWord.Options.BackgroundSave;
        oWord.Options.BackgroundSave = true;
        // kick off a thread and pass in the document object
        bool UiSave = SaveAsUI;                 // have to do this because the bool from Word

        // is passed to us as ByRef
        new Thread(() =>
        {
            Handle_WaitForAfterSave(Doc, UiSave);
        }).Start();
    }
示例#2
0
        /// <summary>
        /// Replace the property name
        /// </summary>
        /// <param name="vkFind"></param>
        /// <param name="vkReplace"></param>
        /// <param name="vkNum"></param>
        /// <param name="vkWordApp"></param>
        /// <param name="vkMyDoc"></param>
        public static void ReplaceProperty(
            object vkFind,
            object vkReplace,
            object vkNum,
            Word.Application vkWordApp,
            Word.Document vkMyDoc
            )
        {
            if (vkMyDoc == null)
            {
                return;
            }
            if (vkWordApp == null)
            {
                return;
            }

            if (vkFind.ToString().Trim().Length == 0)
            {
                return;
            }

            object oDocCustomProps;
            string propertyName  = vkFind.ToString().Trim();
            string propertyValue = vkReplace.ToString().Trim();

            // -- change code from here -- //
            // It works however the propertyName must be defined in the document first otherwise it won't work.
            //

            var properties = vkMyDoc.CustomDocumentProperties;

            properties[propertyName].Value = propertyValue;
        }
示例#3
0
        private void b_save_Click(object sender, EventArgs e)
        {
            SaveFileDialog save_file_dialog = new SaveFileDialog();

            save_file_dialog.Filter = "Microsoft Word Files (*.doc)|*.doc" +
                                      "| Microsoft Word Compressed Files (*.docx)|*.docx";
            save_file_dialog.DefaultExt = "doc";
            if (save_file_dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
                save_file_dialog.FileName.Length > 0)
            {
                //Сохраняем документ
                Word.Application app = new Word.Application();
                app.Visible = false;
                Word.Document doc = app.Documents.Add();
                doc.Paragraphs[1].Range.Text = this.text_box.Text;

                for (int i = 1; i < doc.Paragraphs.Count; ++i)
                {
                    doc.Paragraphs[i].Range.Font.Name = "Times New Roman";
                    doc.Paragraphs[i].Range.Font.Size = 14;
                }

                doc.SaveAs2(save_file_dialog.FileName);
                doc.Close();
                app.Quit();
            }
        }
示例#4
0
        public void InsertBT()
        {
            object missing = System.Reflection.Missing.Value;

            Word._Application app  = new Word.Application();
            object            path = RandomPath;

            //object fileName = @"\tmp\show.doc";
            // Word.Document doc = app.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);

            //doc.Activate();
            Word.Document doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            doc.Activate();
            Word.Range range = doc.Paragraphs.Last.Range;                                       //定位到段尾
            range.Text = "脚手架专项施工方案";
            range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //文字居中
            //object styleName = "标题 2";
            // range.set_Style(ref styleName);
            range.Font.Size = 20;
            range.Font.Name = "黑体";
            range.Font.Bold = 1;

            doc.SaveAs(ref path, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            app.Quit(ref missing, ref missing, ref missing);
            InsertFile(path.ToString());

            //range.InsertParagraphAfter();
        }
示例#5
0
        // ---------------------------------------------
        //             Open Document
        // ---------------------------------------------
        public static void OpenDocument(object fromFileName, object vkReadOnly)
        {
            if (!File.Exists((string)fromFileName))
            {
                MessageBox.Show("File not found. " + fromFileName);
                return;
            }


            Word.Application vkWordApp =
                new Word.Application();

            // object vkReadOnly = false;
            object vkVisible = true;
            object vkFalse   = false;
            object vkTrue    = true;
            object vkDynamic = 2;


            object vkMissing = System.Reflection.Missing.Value;

            // Let's make the word application visible
            vkWordApp.Visible = true;
            vkWordApp.Activate();

            // Let's open the document
            Word.Document vkMyDoc = vkWordApp.Documents.Open(
                ref fromFileName, ref vkMissing, ref vkReadOnly,
                ref vkMissing, ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkMissing, ref vkVisible);

            return;
        }
示例#6
0
        //把Word文档转换为Pdf文档
        #region
        private static void WordToPdf(string WordfileName, string PdfFileName)
        {
            //Object missing = System.Reflection.Missing.Value;
            //object bSave = false;

            //WPS.Application app = new WPS.Application();
            //app.Visible = false;

            //WPS.Document doc = app.Documents.Open(WordfileName, false, true, false, "", "", false, "", "", 0, 0, false, false, 0, false);

            //doc.ExportPdf(PdfFileName, "", "");


            //app.Quit(ref bSave, ref missing, ref missing);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
            //app = null;


            Object missing = System.Reflection.Missing.Value;
            object bSave   = false;

            Word.Application app = new Word.Application();//应用对象 
            //WPS.Application app = new WPS.Application();
            app.Visible = false;

            Word.Document doc = app.Documents.Open(WordfileName, false, true, false, "", "", false, "", "", 0, 0, false, false, 0, false);

            doc.ExportAsFixedFormat(PdfFileName, Word.WdExportFormat.wdExportFormatPDF);


            app.Quit(ref bSave, ref missing, ref missing);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
            app = null;
        }
示例#7
0
文件: Form1.cs 项目: a-vodka/ics
 private void button2_Click(object sender, EventArgs e)
 {
     wordApp.Visible = true;
     Word.Document wd = wordApp.Documents.Add();
     wd.Range().Text = "Hello word!";
     wd.Range().Font.Size = 64;
 }
示例#8
0
        public static void FindAndReplaceYS(
            object vkFind,
            object vkReplace,
            object vkNum,
            Word.Application vkWordApp,
            Word.Document vkMyDoc
            )
        {
            object vkReadOnly = false;
            object vkVisible  = true;
            object vkFalse    = false;
            object missing    = false;
            object vkTrue     = true;
            object vkDynamic  = 2;
            object replaceAll = Word.WdReplace.wdReplaceAll;

            // Replace Word Document body
            //

            vkWordApp.Selection.Find.ClearFormatting();
            vkWordApp.Selection.Find.Text = vkFind.ToString();

            vkWordApp.Selection.Find.Replacement.ClearFormatting();
            vkWordApp.Selection.Find.Replacement.Text = vkFind.ToString();

            vkWordApp.Selection.Find.Execute(
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref replaceAll, ref missing, ref missing, ref missing, ref missing);
        }
		/// <summary>
		/// catches Word's close event 
		/// starts a Thread that send a ESC to the word window ;)
		/// </summary>
		/// <param name="doc"></param>
		/// <param name="test"></param>
		private void OnClose(Word.Document doc, ref bool chancel)
		{
			if(!deactivateevents)
			{
				chancel=true;
			}
		}
 void WordApp_DocumentOpen(Word.Document Doc)
 {
     if (isPaneRequired(Doc))
     {
         ShowSomeSortOfPane();
     }
 }
示例#11
0
 /// <summary>
 /// catches Word's close event
 /// starts a Thread that send a ESC to the word window ;)
 /// </summary>
 /// <param name="pDoc"></param>
 /// <param name="test"></param>
 private void OnClose(Word.Document pDoc, ref bool pCancel)
 {
     if (!deactivateevents)
     {
         pCancel = true;
     }
 }
        ///
        /// 创建文档
        ///
        public void CreateAWord()
        {
            //实例化word应用对象
            this._wordApplication = new Word.ApplicationClass();
            Object myNothing = System.Reflection.Missing.Value;

            this._wordDocument = this._wordApplication.Documents.Add(ref myNothing, ref myNothing, ref myNothing, ref myNothing);
        }
示例#13
0
 /// <summary>
 /// WPS组件
 /// </summary>
 /// <param name="sourcePath"></param>
 /// <param name="targetPath"></param>
 public void WPSWordToPdf(string sourcePath, string targetPath)
 {
     app = new Word.ApplicationClass();
     Word.Document doc = app.Documents.Open(sourcePath, Visible: false);
     doc.ExportAsFixedFormat(targetPath, Word.WdExportFormat.wdExportFormatPDF);
     doc.Close();
     app.Quit();
 }
示例#14
0
        // Open a new document
        public void Open( )
        {
            object missing = System.Reflection.Missing.Value;

            oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            oDoc.Activate();
        }
        /// 
        /// 创建文档 
        ///
        public void CreateAWord()
        {
            //实例化word应用对象
            this._wordApplication = new Word.ApplicationClass();
            Object myNothing = System.Reflection.Missing.Value;

            this._wordDocument = this._wordApplication.Documents.Add(ref myNothing, ref myNothing, ref myNothing, ref myNothing);
        }
示例#16
0
        // ----------------------------------------------------
        //         Replace strings in structure
        // ----------------------------------------------------
        static public void ReplaceStringInAllFiles(
            string originalFolder,
            List <TagStructure> tagList,
            Word.Application vkWordApp)
        {
            object vkMissing  = System.Reflection.Missing.Value;
            object vkReadOnly = false;
            object vkVisible  = true;
            object vkFalse    = false;

            if (Directory.Exists(originalFolder))
            {
                string[] files = Directory.GetFiles(originalFolder);
                foreach (string file in files)
                {
                    string name  = Path.GetFileName(file);
                    object xFile = file;

                    // Let's open the document
                    Word.Document vkMyDoc = vkWordApp.Documents.Open(
                        ref xFile, ref vkMissing, ref vkReadOnly,
                        ref vkMissing, ref vkMissing, ref vkMissing,
                        ref vkMissing, ref vkMissing, ref vkMissing,
                        ref vkMissing, ref vkMissing, ref vkVisible);

                    vkMyDoc.Select();

                    if (tagList.Count > 0)
                    {
                        for (int i = 0; i < tagList.Count; i++)
                        {
                            FindAndReplace(
                                tagList[i].Tag,
                                tagList[i].TagValue,
                                1,
                                vkWordApp,
                                vkMyDoc);
                        }
                    }

                    WordDocumentTasks.insertPicture(vkMyDoc, "C:\\Research\\fcm\\Resources\\FCMLogo.jpg", "");
                    vkMyDoc.Save();
                    vkMyDoc.Close(ref vkFalse, ref vkMissing, ref vkMissing);
                }

                //
                //  Replace in all folders
                //
                string[] folders = Directory.GetDirectories(originalFolder);
                foreach (string folder in folders)
                {
                    ReplaceStringInAllFiles(folder,
                                            tagList,
                                            vkWordApp);
                }
            }
        }
示例#17
0
		/// <summary>
		/// catches Word's newdocument event
		/// just close
		/// </summary>
		/// <param name="doc"></param>
		private void OnNewDoc(Word.Document doc)
		{
			if(!deactivateevents)
			{
				deactivateevents=true;
				object dummy = null;
				doc.Close(ref dummy,ref dummy,ref dummy);
				deactivateevents=false;
			}
		}
 // in your button click handler, just call PrintOut() function
 private void ButtonClickHandler(object sender, EventArgs e)
 {
     // if doc == null, open the document
     if (doc == null)
     {
         // here i assume fileName has been assigned
         doc = word.Documents.Open(fileName, ReadOnly: readOnly, Visible: isVisible);
     }
     doc.PrintOut();
 }
 void wsh_AfterSaveEvent(Word.Document doc, bool isClosed)
 {
     if (!isClosed)
     {
         MessageBox.Show("After Save Event");
     }
     else
     {
         MessageBox.Show("After Close and Save Event. The filname was: " + wsh.ClosedFilename);
     }
 }
示例#20
0
        // ----------------------------------------------------
        //         Insert picture
        // ----------------------------------------------------
        public static void insertPicture(Word.Document oDoc,
                                         string pictureFile,
                                         object bookMarkName
                                         )
        {
            // 02.03.2013
            // Inserting pictures is on hold
            // PICTUREHOLD

            LogFile.WriteToTodaysLogFile(
                "Error: Pictures and logos are not being replace at this time. Issues are being investigated.", "", "", "WordDocumentTasks.cs");
            return;



            object oMissing = System.Reflection.Missing.Value;

            if (pictureFile == "\\" || pictureFile == "\\\\" || string.IsNullOrEmpty(pictureFile))
            {
                return;
            }

            // oDoc.ActiveWindow.Selection.Range.InlineShapes.AddPicture(
            //     pictureFile, ref oMissing, ref oMissing, ref oMissing);

            // Object bookMarkName = "COMPANY_LOGO";

            if (oDoc.Bookmarks.Exists(bookMarkName.ToString()))
            {
                //oDoc.Bookmarks.Item(ref bookMarkName).Range.InlineShapes.AddPicture(
                //    pictureFile, ref oMissing, ref oMissing, ref oMissing);

                try
                {
                    //oDoc.Bookmarks.Item(ref bookMarkName).Range.InlineShapes.AddPicture(
                    //    FileName: pictureFile,
                    //    LinkToFile: oMissing,
                    //    SaveWithDocument: oMissing,
                    //    Range: oMissing);

                    oDoc.Bookmarks.Item(ref bookMarkName).Range.InlineShapes.AddPicture(
                        FileName: pictureFile,
                        LinkToFile: oMissing,
                        SaveWithDocument: oMissing,
                        Range: oMissing);
                }
                catch (Exception ex)
                {
                    LogFile.WriteToTodaysLogFile("insertPicture " + ex, "", "", "WordDocumentTasks.cs");
                }
            }
            // Object oMissed = doc.Paragraphs[2].Range; //the position you want to insert
            // doc.InlineShapes.AddPicture(
        }
        private void SaveToWordFile(string path, string text, decimal numOfVersion, FileContent fileContent)
        {
            //Создаем новый вордовский документ
            Word.Document doc = _app.Documents.Add();
            doc.Paragraphs[1].Range.Text = text;

            for (int i = 1; i <= doc.Paragraphs.Count; ++i)
            {
                doc.Paragraphs[i].Range.Font.Name = "Times New Roman";
                doc.Paragraphs[i].Range.Font.Size = 14;
            }

            //Генерируем название документа в зависимости от его содержимого (ответы или варианты)
            string title;

            if (fileContent == FileContent.Answers)
            {
                title = path + @"\Вариант " + numOfVersion + " ответы.docx";
            }
            else
            {
                title = path + @"\Вариант " + numOfVersion + ".docx";
            }

            if (File.Exists(title) && _applyToAll == false)                                        //Если файл с таким именем уже существует
            {
                UsersConfirmForms usersConfirm = new UsersConfirmForms(numOfVersion, fileContent); //Открываем окно, в котором
                                                                                                   //спрашиваем пользователя,
                                                                                                   //что делать
                _applyToAll             = usersConfirm.ApplyToAll;
                _usersConfirmFormResult = usersConfirm.ShowDialog();

                if (_usersConfirmFormResult == DialogResult.Cancel)
                {
                    doc.Close();
                    return;
                }
            }

            if (_usersConfirmFormResult == DialogResult.No)               //Если пользователь решил сохранить оба документа
            {
                string finalTitle = setTitle(title);                      //Настраиваем название файла в зависимости от того, существуют ли файлы с таким
                                                                          //же названием
                finalTitle = finalTitle.Remove(finalTitle.Length - 5, 5); //Убираем расширение .docx из названия файла
                doc.SaveAs2(finalTitle);
            }
            else
            {
                doc.SaveAs2(title);
            }

            doc.Close();
        }
示例#22
0
    public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks)
    {
        Word._Application wordApplication = new Word.Application();
        object            pageBreak       = Word.WdBreakType.wdSectionBreakContinuous;
        object            outputFile      = outputFilename;
        object            fileName        = @"S:\ODS\Insight 2 Oncology\Quality Division Project\Visual Review Scores\Scoring Template\MergeTemplate.docx";
        object            end             = Word.WdCollapseDirection.wdCollapseEnd;

        try
        {
            wordApplication.Visible = false;
            Word.Document  wordDocument = wordApplication.Documents.Add(ref fileName);
            Word.Selection selection    = wordApplication.Selection;

            foreach (string file in filesToMerge)
            {
                if (file.Contains("Scores.docx"))
                {
                    selection.PageSetup.PaperSize   = Word.WdPaperSize.wdPaper11x17;
                    selection.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
                    selection.InsertFile(file);
                    selection.Collapse(ref end);
                }
                if (!file.Contains("Scores.docx") && insertPageBreaks)
                {
                    selection.InsertFile(file);
                    selection.InsertBreak(pageBreak);
                }
            }
            wordApplication.Selection.Document.Content.Select();
            wordDocument.PageSetup.TopMargin          = (float)50;
            wordDocument.PageSetup.RightMargin        = (float)50;
            wordDocument.PageSetup.LeftMargin         = (float)50;
            wordDocument.PageSetup.BottomMargin       = (float)50;
            selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
            selection.ParagraphFormat.SpaceAfter      = 0.0F;
            selection.ParagraphFormat.SpaceBefore     = 0.0F;
            wordDocument.SaveAs(outputFile + ".docx");
            wordDocument.Close();
            wordDocument = wordApplication.Documents.Open(outputFile + ".docx");
            wordDocument.ExportAsFixedFormat(outputFile + ".pdf", Word.WdExportFormat.wdExportFormatPDF);
            wordDocument = null;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            wordApplication.Quit();
        }
    }
        // Open a file (the file must exists) and activate it
        public void Open(string strFileName)
        {
            object fileName  = strFileName;
            object readOnly  = false;
            object isVisible = true;
            object missing   = System.Reflection.Missing.Value;

            oDoc = oWordApplic.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);

            oDoc.Activate();
        }
示例#24
0
    /// <summary>
    /// Extracts the review results from a Word document
    /// </summary>
    /// <param name="fileName">Fully qualified path of the file to be evaluated</param>
    /// <returns></returns>
    public ReviewResult GetReviewResults(string fileName)
    {
        Word.Application  wordApp     = null;
        List <ReviewItem> reviewItems = new List <ReviewItem>();
        object            missing     = System.Reflection.Missing.Value;

        try
        {
            // Fire up Word
            wordApp = new Word.ApplicationClass();
            // Some object variables because the Word API requires this
            object fileNameForWord = fileName;
            object readOnly        = true;
            WorkingDoc = wordApp.Documents.Open(ref fileNameForWord,
                                                ref missing, ref readOnly,
                                                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);
            // Gather all paragraphs that are chapter headers, sorted by their start position
            var headers = (from Word.Paragraph p in WorkingDoc.Paragraphs
                           where IsHeading(p)
                           select new Heading()
            {
                Text = GetHeading(p),
                Start = p.Range.Start
            }).ToList().OrderBy(h => h.Start);
            reviewItems.AddRange(FindComments(headers));
            // I will be doing similar things with Revisions in the document
        }
        catch (Exception x)
        {
            MessageBox.Show(x.ToString(),
                            "Error while collecting review items",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
        }
        finally
        {
            if (wordApp != null)
            {
                object doNotSave = Word.WdSaveOptions.wdDoNotSaveChanges;
                wordApp.Quit(ref doNotSave, ref missing, ref missing);
            }
        }
        ReviewResult result = new ReviewResult();

        result.Items = reviewItems.OrderBy(i => i.Position);
        return(result);
    }
示例#25
0
        public void Quit( )
        {
            object missing = System.Reflection.Missing.Value;

            if (oDoc != null)
            {
                oDoc.Close(ref missing, ref missing, ref missing);
                oDoc = null;
            }
            if (oWordApplic != null)
            {
                oWordApplic.Application.Quit(ref missing, ref missing, ref missing);
                oWordApplic = null;
            }
        }
示例#26
0
        // ---------------------------------------------
        //             Copy Documents
        // ---------------------------------------------
        public static object CopyDocument(
            object fromFileName,
            object destinationFileName,
            List <WordDocumentTasks.TagStructure> tag
            )
        {
            Word.Application vkWordApp =
                new Word.Application();

            object saveFile = destinationFileName;

            object vkReadOnly = false;
            object vkVisible  = true;
            object vkFalse    = false;
            object vkTrue     = true;
            object vkDynamic  = 2;

            object vkMissing = System.Reflection.Missing.Value;

            // Let's make the word application visible
            vkWordApp.Visible = true;
            vkWordApp.Activate();

            // Let's copy the document
            File.Copy(fromFileName.ToString(), destinationFileName.ToString(), true);

            // Let's open the DESTINATION document
            Word.Document vkMyDoc = vkWordApp.Documents.Open(
                ref destinationFileName, ref vkMissing, ref vkReadOnly,
                ref vkMissing, ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkMissing, ref vkMissing,
                ref vkMissing, ref vkMissing, ref vkVisible);

            foreach (var t in tag)
            {
                FindAndReplace(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc);
            }

            vkMyDoc.Save();

            // close the new document
            vkMyDoc.Close(ref vkFalse, ref vkMissing, ref vkMissing);

            // close word application
            vkWordApp.Quit(ref vkFalse, ref vkMissing, ref vkMissing);

            return(saveFile);
        }
示例#27
0
        /*
         * Activates a word document.
         */
        public void ActivateDocument(Document slDoc, ProjectServerConnection psc)
        {
            Word.Document wdDoc = null;
            try
            {
                Document slDocDeep = psc.DocumentManager.getDocumentDeep(slDoc.id);

                // Todo: I think part of the problem here is opening one document in word,
                // overwriting that document (FHANDLE, ETC)  and reloading as a new doc
                // with the existing one still open.
                //
                // This should be testable by uploading multiple documents to RoundTable
                // and opening each one.
                FileStream   fs = new FileStream(slDocDeep.filename, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(slDocDeep.document, 0, slDocDeep.document.Length);
                bw.Flush();
                bw.Close();
                fs.Close();                 // Already done by bw?

                // Activate the RoundTable Document.
                object missing  = Type.Missing;
                object filepath = Path.GetFullPath(slDocDeep.filename);
                wdDoc = wordApp.Documents.Open(ref filepath,
                                               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);

                wdDoc.Activate();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                try
                {
                    Marshal.ReleaseComObject(wdDoc);
                }
                catch (Exception ex)
                {
                }
            }
        }
示例#28
0
        public void InsertFile(string path)
        {
            Word.ApplicationClass applicationClass = new Word.ApplicationClass();
            object fileName = showPath;

            Word.Document doct = applicationClass.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);
            doct.Activate();
            object confirmConversion = false;
            object link       = false;
            object attachment = false;

            applicationClass.Selection.InsertFile(path, ref missing, ref confirmConversion, ref link, ref attachment);
            object pBreak = (int)Word.WdBreakType.wdPageBreak;

            applicationClass.Selection.InsertBreak(ref pBreak);
            doct.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            ((Word._Document)doct).Close(ref missing, ref missing, ref missing);
        }
示例#29
0
        //Метод, сохраняющий текст в вордовский файл
        private void SaveToWordFile(string file_name, string text)
        {
            //Открываем ворд на фоне
            Word.Application app = new Word.Application();
            app.Visible = false;
            Word.Document doc = app.Documents.Add();
            doc.Paragraphs[1].Range.Text = text;

            for (int i = 1; i < doc.Paragraphs.Count; ++i)
            {
                doc.Paragraphs[i].Range.Font.Name = "Times New Roman";
                doc.Paragraphs[i].Range.Font.Size = 14;
            }

            doc.SaveAs2(file_name);
            doc.Close();
            app.Quit();
        }
示例#30
0
        private void btnYazdır_Click(object sender, EventArgs e)
        {
            try
            {
                Word.Application WordApp = new Word.Application();
                Word.Document    WordDoc = new Word.Document();

                DataSet ds = new DataSet();
                if (baglantı.State == ConnectionState.Closed)
                {
                    baglantı.Open();
                }

                OleDbCommand    komut  = new OleDbCommand("Select YazarAdi,KitapAdi from kitaplar", baglantı);
                OleDbDataReader reader = komut.ExecuteReader();

                WordDoc         = WordApp.Documents.Open(Application.StartupPath + "\\bos_kitaplar.docx");
                WordApp.Visible = true;
                int i = 2;
                while (reader.Read())
                {
                    WordDoc.Range().Tables[1].Cell(i, 1).Range.InsertAfter(reader["YazarAdi"].ToString());
                    WordDoc.Range().Tables[1].Cell(i, 2).Range.InsertAfter(reader["KitapAdi"].ToString());
                    WordDoc.Range().Tables[1].Rows.Add();
                    i++;
                }
                WordDoc.SaveAs(Application.StartupPath + "\\tum_kitaplar" + ".doc");
                WordDoc.Close();
                WordApp.Quit();

                WordDoc = null;
                WordApp = null;

                MessageBox.Show("Sorular WORD'a aktarıldı!");
                baglantı.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

                baglantı.Close();
            }
        }
    void Application_DocumentBeforeClose(Word.Document document, ref bool Cancel)
    {
        try
        {
            string filePath = this.Application.ActiveDocument.FullName.ToString();
            string fileName = this.Application.ActiveDocument.Name;

            //dialogFilePath = filePath;
            dialogFileName = fileName;
            doc            = document;

            string tempFile;
            string tempPath;

            //var form = new SaveFileDialog();
            //form.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            //form.ShowDialog();
            //System.Windows.Forms.MessageBox.Show(form.ToString());
            //_T is for editing template and save file after saving.
            //+ is for saving

            //document.Save();
            var iPersistFile = (IPersistFile)document;
            iPersistFile.Save(tempPath, false);

            if (filePath.Contains("_T"))
            {
                //Store file into DB
            }
            else
            {
                //Store file into DB
            }
            //object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
            //document.Close(ref doNotSaveChanges, ref missing, ref missing);
            Word._Document wDocument = Application.Documents[fileName] as Word._Document;
            //wDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
            ThisAddIn.doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
        }
        catch (Exception exception)
        {
        }
    }
 public void close()
 {
     this._wordApplication = null;
     this._wordDocument = null;
 }
示例#33
0
        // Open a new document
        public void Open( )
        {
            object missing = System.Reflection.Missing.Value;
            oDoc = oWordApplic.Documents.Add(ref missing, ref missing,ref missing, ref missing);

            oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            oDoc.Activate();
        }
示例#34
0
        // Open a file (the file must exists) and activate it
        public void Open( string strFileName)
        {
            object fileName = strFileName;
            object readOnly = false;
            object isVisible = true;
            object missing = System.Reflection.Missing.Value;

            oDoc = oWordApplic.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);

            oDoc.Activate();
        }
示例#35
0
        /// <summary>
        /// 删除word文档中相应的内容
        /// </summary>
        /// <param name="startText">起始字符</param>
        /// <param name="endText">终止字符</param>
        /// <param name="path">文档路径</param>
        /// <returns></returns>
        public bool DeleteText(string startText, string endText, string path)
        {
            object OBJpath = path;
            object missing = System.Reflection.Missing.Value;
            Word._Application wapp = new Word.ApplicationClass();
            Word.Document wdoc = new Word.Document();
            wdoc = wapp.Documents.Open(ref OBJpath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

            Word.Selection tihuanwenzi = wapp.Selection;

            wapp.Options.ReplaceSelection = true;
            wapp.Selection.Find.Forward = true;
            wapp.Selection.Find.MatchWholeWord = true;
            object startstr = startText;
            object endstr = endText;
            wapp.Selection.Find.ClearFormatting();
            wapp.Selection.Find.Execute(ref startstr, 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);
            object start = wapp.Selection.Range.Start;//定位起始位置
            wapp.Selection.Find.ClearFormatting();
            wapp.Selection.Find.Execute(ref endstr, 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);
            object end = wapp.Selection.Range.End;//定义终止位置
            object unit = Type.Missing;

            object count = Type.Missing;
            wdoc.Range(ref start, ref end).Delete(ref unit, ref count);//删除操作
            object SaveChangs = true;
            object OriginalFormat = System.Type.Missing;
            object RouteDocument = System.Type.Missing;
            wapp.Documents.Close(ref missing, ref missing, ref missing);
            wapp.Quit(ref SaveChangs, ref OriginalFormat, ref RouteDocument);
            return true;
        }
示例#36
0
        /// <summary>
        /// cover file word to body hmtl of mail,which embed fictures
        /// </summary>
        /// <param name="PathWordTemplate">path to word template file</param>
        /// <param name="Mail">Mail is embed body</param>
        /// <returns></returns>
        private static bool HTMLBody(DataSet DataFill, string PathWordTemplate, ref Email Mail)
        {
            string path = FrameworkParams.TEMP_FOLDER + @"\WordTemp";
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);
            path += PathWordTemplate.Substring(PathWordTemplate.LastIndexOf("\\"));
            WordDocument WordDoc = new WordDocument();
            try
            {
                WordDoc.Open(PathWordTemplate);
                for (int i = 0; i < DataFill.Tables.Count; i++)
                {
                    WordDoc.MailMerge.ExecuteGroup(DataFill.Tables[i]);
                }
                WordDoc.Save(path);

                Word.ApplicationClass wd = new Word.ApplicationClass();
                Word.Document document = new Word.Document();
                object fileName = (object)path;
                object newTemplate = false;
                object docType = 0;
                object isVisible = true;
                object missing = System.Reflection.Missing.Value;

                document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);

                object oFileName = (object)(path.Substring(0, path.LastIndexOf(".")) + ".html");
                object oSaveFormat = (object)(Word.WdSaveFormat.wdFormatHTML);

                if (System.IO.File.Exists(oFileName.ToString()))
                    System.IO.File.Delete(oFileName.ToString());

                document.SaveAs(ref oFileName,
                                ref oSaveFormat,
                                ref missing,
                                ref missing,
                                ref missing,
                                ref missing,
                                ref missing,
                                ref missing,
                                ref missing,
                                ref missing,
                                ref missing);
                document.Close(ref missing, ref missing, ref missing);
                wd.Quit(ref missing, ref missing, ref missing);

                Mht mailbody = new Mht();
                mailbody.UnlockComponent("MHT-TEAMBEAN_1E1F4760821H");
                mailbody.UseCids = true;
                Mail = mailbody.GetEmail(oFileName.ToString());

                return true;
            }
            catch
            {
                return false;
            }
        }
示例#37
0
        /// <summary>
        /// Loads a document into the control
        /// </summary>
        /// <param name="t_filename">path to the file (every type word can handle)</param>
        public void LoadDocument(string t_filename)
        {
            deactivateevents = true;
            filename = t_filename;

            if(wd == null) wd = new Word.ApplicationClass();
            try
            {
                wd.CommandBars.AdaptiveMenus = false;
                wd.DocumentBeforeClose += new Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(OnClose);
                //wd.OnNewDocument += new Word.ApplicationEvents4_NewDocumentEventHandler(OnNewDoc);
                wd.DocumentOpen+= new Word.ApplicationEvents4_DocumentOpenEventHandler(OnOpenDoc);
                wd.ApplicationEvents2_Event_Quit += new Word.ApplicationEvents2_QuitEventHandler(OnQuit);
            }
            catch{}

            if(document != null)
            {
                try
                {
                    object dummy=null;
                    wd.Documents.Close(ref dummy, ref dummy, ref dummy);
                }
                catch{}
            }

            if( wordWnd==0 ) wordWnd = FindWindow( "Opusapp", null);
            if (wordWnd!=0)
            {
                SetParent( wordWnd, this.Handle.ToInt32());

                object fileName = filename;
                object newTemplate = false;
                object docType = 0;
                object readOnly = true;
                object isVisible = true;
                object missing = System.Reflection.Missing.Value;

                try
                {
                    if( wd == null )
                    {
                        throw new WordInstanceException();
                    }

                    if( wd.Documents == null )
                    {
                        throw new DocumentInstanceException();
                    }

                    if( wd != null && wd.Documents != null )
                    {
                        document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
                    }

                    if(document == null)
                    {
                        throw new ValidDocumentException();
                    }
                }
                catch
                {
                }

                try
                {
                    wd.ActiveWindow.DisplayRightRuler=false;
                    wd.ActiveWindow.DisplayScreenTips=false;
                    wd.ActiveWindow.DisplayVerticalRuler=false;
                    wd.ActiveWindow.DisplayRightRuler=false;
                    wd.ActiveWindow.ActivePane.DisplayRulers=false;
                    wd.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdWebView; // .wdNormalView;
                }
                catch
                {

                }

                /*
                int counter = wd.ActiveWindow.Application.CommandBars.Count;
                for(int i = 0; i < counter;i++)
                {
                    try
                    {
                        wd.ActiveWindow.Application.CommandBars[i].Enabled=false;
                    }
                    catch
                    {

                    }
                }
                */
                try
                {
                    wd.Visible = true;
                    wd.Activate();

                    SetWindowPos(wordWnd,this.Handle.ToInt32(),0,0,this.Bounds.Width+20,this.Bounds.Height+20, SWP_NOZORDER | SWP_NOMOVE | SWP_DRAWFRAME);
                    MoveWindow(wordWnd,-5,-33,this.Bounds.Width+10,this.Bounds.Height+57,true);
                }
                catch
                {
                    MessageBox.Show("Error: do not load the document into the control until the parent window is shown!");
                }
                this.Parent.Focus();

            }
            deactivateevents = false;
        }
示例#38
0
        /// <summary>
        /// Close the current Document in the control --> you can 
        /// load a new one with LoadDocument
        /// </summary>
        public void ExitMicrosoftWord()
        {
            if (wd == null) return;
            try
            {
                deactivateevents = true;

                object dummy = null;
                object dummy2 = (object)false;
                document.Close(ref dummy, ref dummy, ref dummy);
                // Change the line below.
                wd.Quit(ref dummy2, ref dummy, ref dummy);

                deactivateevents = false;
            }
            catch (Exception ex)
            {
                //String strErr = ex.Message;
            }
            finally
            {
                this.document = null;
                this.wordWnd = 0;
                wd = null;
            }
        }
示例#39
0
        /// <summary>Loads a document into the control
        /// </summary>
        /// <param name="t_filename">path to the file (every type word can handle)</param>
        public void OpenDocument(string t_filename)
        {
            deactivateevents = true;

            filename = t_filename;
            try
            {
                RunMicrosoftWord();

                wd.CommandBars.AdaptiveMenus = false;
                wd.DocumentBeforeClose += new Word.ApplicationEvents2_DocumentBeforeCloseEventHandler(OnClose);
                wd.NewDocument += new Word.ApplicationEvents2_NewDocumentEventHandler(OnNewDoc);
                wd.DocumentOpen += new Word.ApplicationEvents2_DocumentOpenEventHandler(OnOpenDoc);
                wd.ApplicationEvents2_Event_Quit += new Word.ApplicationEvents2_QuitEventHandler(OnQuit);

                if (document != null){
                    try{
                        object dummy = null;
                        wd.Documents.Close(ref dummy, ref dummy, ref dummy);
                    } catch { }
                }
            }
            catch { }
            if (wordWnd == 0) wordWnd = FindWindow("Opusapp", null);
            if (wordWnd != 0)
            {
                SetParent(wordWnd, this.Handle.ToInt32());

                object fileName = filename;
                object newTemplate = false;
                object docType = 0;
                object readOnly = true;
                object isVisible = true;
                object missing = System.Reflection.Missing.Value;

                try
                {
                    if (wd == null) { throw new WordInstanceException(); }

                    if (wd.Documents == null) { throw new DocumentInstanceException(); }

                    if (wd != null && wd.Documents != null){
                        document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
                    }

                    if (document == null) { throw new ValidDocumentException(); }
                }
                catch { }

                #region Dữ liệu ko dùng tham khảo
                //try
                //{
                //    wd.ActiveWindow.DisplayRightRuler=false;
                //    wd.ActiveWindow.DisplayScreenTips=false;
                //    wd.ActiveWindow.DisplayVerticalRuler=false;
                //    wd.ActiveWindow.DisplayRightRuler=false;
                //    wd.ActiveWindow.ActivePane.DisplayRulers=false;
                //    wd.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdWebView;
                //    //wd.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdPrintView;//wdWebView; // .wdNormalView;
                //}
                //catch
                //{
                //}
                ///// Code Added
                ///// Disable the specific buttons of the command bar
                ///// By default, we disable/hide the menu bar
                ///// The New/Open buttons of the command bar are disabled
                ///// Other things can be added as required (and supported ..:) )
                ///// Lots of commented code in here, if somebody needs to disable specific menu or sub-menu items.
                /////
                //int counter = wd.ActiveWindow.Application.CommandBars.Count;
                //for(int i = 1; i <= counter;i++)
                //{
                //    try
                //    {
                //        String nm=wd.ActiveWindow.Application.CommandBars[i].Name;
                //        if(nm=="Standard")
                //        {
                //            //nm=i.ToString()+" "+nm;
                //            //MessageBox.Show(nm);
                //            int count_control=wd.ActiveWindow.Application.CommandBars[i].Controls.Count;
                //            for(int j=1;j<=2;j++)
                //            {
                //                //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].ToString());
                //                wd.ActiveWindow.Application.CommandBars[i].Controls[j].Enabled=false;
                //            }
                //        }

                //        if(nm=="Menu Bar")
                //        {
                //            //To disable the menubar, use the following (1) line
                //            wd.ActiveWindow.Application.CommandBars[i].Enabled=false;

                //            /// If you want to have specific menu or sub-menu items, write the code here.
                //            /// Samples commented below

                //            //							MessageBox.Show(nm);
                //            //int count_control=wd.ActiveWindow.Application.CommandBars[i].Controls.Count;
                //            //MessageBox.Show(count_control.ToString());

                //            /*
                //            for(int j=1;j<=count_control;j++)
                //            {
                //                /// The following can be used to disable specific menuitems in the menubar
                //                /// wd.ActiveWindow.Application.CommandBars[i].Controls[j].Enabled=false;

                //                //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].ToString());
                //                //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].Caption);
                //                //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].accChildCount.ToString());

                //                ///The following can be used to disable some or all the sub-menuitems in the menubar

                //                ////Office.CommandBarPopup c;
                //                ////c = (Office.CommandBarPopup)wd.ActiveWindow.Application.CommandBars[i].Controls[j];
                //                ////
                //                ////for(int k=1;k<=c.Controls.Count;k++)
                //                ////{
                //                ////	//MessageBox.Show(k.ToString()+" "+c.Controls[k].Caption + " -- " + c.Controls[k].DescriptionText + " -- " );
                //                ////	try
                //                ////	{
                //                ////		c.Controls[k].Enabled=false;
                //                ////		c.Controls["Close Window"].Enabled=false;
                //                ////	}
                //                ////	catch
                //                ////	{
                //                ////
                //                ////	}
                //                ////}
                //                    //wd.ActiveWindow.Application.CommandBars[i].Controls[j].Control	 Controls[0].Enabled=false;
                //                }
                //                */

                //            }

                //        nm="";
                //    }
                //    catch(Exception ex)
                //    {
                //        MessageBox.Show(ex.ToString());
                //    }
                //}
                #endregion
                // Show the word-document
                try
                {
                    wd.Visible = true;
                    wd.Activate();

                    SetWindowPos(wordWnd, this.Handle.ToInt32(), 0, 0, this.Bounds.Width, this.Bounds.Height, SWP_NOZORDER | SWP_NOMOVE | SWP_DRAWFRAME | SWP_NOSIZE);

                    //Call onresize--I dont want to write the same lines twice
                    OnResize();
                }
                catch
                {
                    MessageBox.Show("Error: do not load the document into the control until the parent window is shown!");
                }
                #region Đoạn code không dùng
                ///// We want to remove the system menu also. The title bar is not visible, but we want to avoid accidental minimize, maximize, etc ..by disabling the system menu(Alt+Space)
                //try
                //{
                //    int hMenu = GetSystemMenu(wordWnd, false);
                //    if(hMenu>0)
                //    {
                //        int	menuItemCount = GetMenuItemCount(hMenu);
                //        RemoveMenu(hMenu, menuItemCount - 1, MF_REMOVE | MF_BYPOSITION);
                //        RemoveMenu(hMenu, menuItemCount - 2, MF_REMOVE | MF_BYPOSITION);
                //        RemoveMenu(hMenu, menuItemCount - 3, MF_REMOVE | MF_BYPOSITION);
                //        RemoveMenu(hMenu, menuItemCount - 4, MF_REMOVE | MF_BYPOSITION);
                //        RemoveMenu(hMenu, menuItemCount - 5, MF_REMOVE | MF_BYPOSITION);
                //        RemoveMenu(hMenu, menuItemCount - 6, MF_REMOVE | MF_BYPOSITION);
                //        RemoveMenu(hMenu, menuItemCount - 7, MF_REMOVE | MF_BYPOSITION);
                //        RemoveMenu(hMenu, menuItemCount - 8, MF_REMOVE | MF_BYPOSITION);
                //        DrawMenuBar(wordWnd);
                //    }
                //}
                //catch{};
                #endregion
                this.Parent.Focus();
            }

            deactivateevents = false;
        }