Ejemplo n.º 1
0
        private void WordReplace(string filePath, string strOld, string strNew)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            object nullobj = System.Reflection.Missing.Value;
            object file    = filePath;

            Microsoft.Office.Interop.Word._Document doc = app.Documents.Open(
                ref file, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj, ref nullobj) as Microsoft.Office.Interop.Word._Document;

            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();
            app.Selection.Find.Text             = strOld;
            app.Selection.Find.Replacement.Text = strNew;

            object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;

            app.Selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj,
                                       ref nullobj, ref nullobj, ref nullobj,
                                       ref nullobj, ref nullobj, ref nullobj,
                                       ref nullobj, ref objReplace, ref nullobj,
                                       ref nullobj, ref nullobj, ref nullobj);
            doc.Save();
            doc.Close(ref nullobj, ref nullobj, ref nullobj);

            app.Quit(ref nullobj, ref nullobj, ref nullobj);
        }
Ejemplo n.º 2
0
        private void save()
        {
            this.Enabled = false;


            Directory.CreateDirectory(".\\" + main.companyName + "\\wjgl\\307\\" + a0.Text + "");

            string temp = System.IO.Directory.GetCurrentDirectory();// d当前运行路径

            //    MessageBox.Show(temp);
            string OrignFile;//word模板路径

            OrignFile = "\\baseDB\\商标书式\\5 补证撤三出具证明\\07 撤销成为商品服务通用名称注册商标申请书.dot";

            //开始写入数据

            string parFilePath = temp + OrignFile;//文件路径
            object FilePath    = parFilePath;

            Microsoft.Office.Interop.Word._Application AppliApp = new Microsoft.Office.Interop.Word.Application();
            AppliApp.Visible = false;
            Microsoft.Office.Interop.Word._Document doc = AppliApp.Documents.Add(ref FilePath);
            object missing    = System.Reflection.Missing.Value;
            object isReadOnly = false;



            doc.Activate();

            //数据写入代码段


            object aa = temp + "\\" + main.companyName + "\\wjgl\\307\\" + a0.Text + "\\" + a0.Text + ".docx";

            object[] MyBM = new object[12]; //创建一个书签数组

            for (int i = 0; i < 12; i++)    //给书签数组赋值
            {
                MyBM[i] = "a" + (i + 1).ToString();
            }



            //给对应的书签位置写入数据
            doc.Bookmarks.get_Item(ref MyBM[0]).Range.Text  = a1.Text;
            doc.Bookmarks.get_Item(ref MyBM[1]).Range.Text  = a2.Text;
            doc.Bookmarks.get_Item(ref MyBM[2]).Range.Text  = a3.Text;
            doc.Bookmarks.get_Item(ref MyBM[3]).Range.Text  = a4.Text;
            doc.Bookmarks.get_Item(ref MyBM[4]).Range.Text  = a5.Text;
            doc.Bookmarks.get_Item(ref MyBM[5]).Range.Text  = a6.Text;
            doc.Bookmarks.get_Item(ref MyBM[6]).Range.Text  = a7.Text;
            doc.Bookmarks.get_Item(ref MyBM[7]).Range.Text  = a8.Text;
            doc.Bookmarks.get_Item(ref MyBM[8]).Range.Text  = a9.Text;
            doc.Bookmarks.get_Item(ref MyBM[9]).Range.Text  = a10.Text;
            doc.Bookmarks.get_Item(ref MyBM[10]).Range.Text = a11.Text;
            doc.Bookmarks.get_Item(ref MyBM[11]).Range.Text = a12.Text;
            doc.SaveAs(ref aa);
            doc.Close();
            this.Enabled = true;
        }
Ejemplo n.º 3
0
 public MakeDictionary()
 {
     this.m_WordApp         = new Microsoft.Office.Interop.Word.Application();
     this.m_WordApp.Visible = true;
     this.m_WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oTrue);
     this.m_Document = this.m_WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oTrue);
 }
Ejemplo n.º 4
0
        public static bool ReadWordText(Microsoft.Office.Interop.Word._Application app, string filePath, out string docText)
        {
            docText = string.Empty;
            try
            {
                Microsoft.Office.Interop.Word._Document doc = null;//实例化一个新的word文档
                object unknow             = Type.Missing;
                object paramSourceDocPath = filePath;
                object ConfirmConversions = false;
                object readOnly           = true;
                object AddToRecentFiles   = false;
                object Visible            = false;
                object Revert             = false;
                object Format             = Microsoft.Office.Interop.Word.WdOpenFormat.wdOpenFormatAuto;
                object OpenAndRepair      = false;
                object NoEncodingDialog   = true;
                doc = app.Documents.Open(ref paramSourceDocPath,
                                         ref ConfirmConversions, ref readOnly, ref AddToRecentFiles, ref unknow, ref unknow,
                                         ref Revert, ref unknow, ref unknow, ref Format, ref unknow,
                                         ref Visible, ref OpenAndRepair, ref NoEncodingDialog, ref unknow, ref unknow);

                if (doc != null)
                {
                    docText = doc.Content.Text + " ";//将全篇内容存入字符串中,最后补一个空格,表示文档能够打开
                    doc.Close(ref unknow, ref unknow, ref unknow);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(false);
        }
Ejemplo n.º 5
0
        public void FindNextSpellingError()
        {
            this.m_CurrentPropertyIndex += 1;
            if (this.m_CurrentPropertyIndex == this.m_SpellCheckList.Count)
            {
                return;
            }
            else
            {
                object value = this.m_SpellCheckList[this.m_CurrentPropertyIndex].Property.GetValue(this.m_DataObject, null);

                Microsoft.Office.Interop.Word._Document document = this.m_WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oFalse);
                document.Words.First.InsertBefore(value.ToString());
                Microsoft.Office.Interop.Word.ProofreadingErrors spellingErrors = document.SpellingErrors;

                if (spellingErrors.Count > 0)
                {
                    document.CheckSpelling(ref oMissing, ref oMissing, ref oMissing,
                                           ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                           ref oMissing, ref oMissing, ref oMissing,
                                           ref oMissing, ref oMissing);

                    object oFirst = 0;
                    object oLast  = document.Characters.Count - 1;

                    string text = document.Range(ref oFirst, ref oLast).Text;
                    this.m_SpellCheckList[this.m_CurrentPropertyIndex].Property.SetValue(this.m_DataObject, text, null);
                }
            }
            this.FindNextSpellingError();
        }
Ejemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="templatePath"></param>
        /// <param name="destDirName"></param>
        private void CreateDesignFile(string templatePath, string destDirName)
        {
            string sourceFile = "";
            string destFile   = "";

            sourceFile = templatePath + SysData.FileName.DESIGN;
            destFile   = destDirName + this.task.Description + DateTime.Now.ToString(@"-设计说明书yyyyMMdd") + ".doc";
            File.Copy(sourceFile, destFile);
            log.Info("设计文档创建成功");

            WordHelper wHelper = new WordHelper();

            Microsoft.Office.Interop.Word._Document oDoc = wHelper.Load(destFile);

            //获取模板中所有的书签
            Microsoft.Office.Interop.Word.Bookmarks bookMarks = oDoc.Bookmarks;
            foreach (Microsoft.Office.Interop.Word.Bookmark bm in bookMarks)
            {
                bm.Select();
                bm.Range.Text = GetContentFromTag(bm.Name);
            }

            object filename = destFile;

            try
            {
                wHelper.Save(oDoc);
                wHelper.Close(oDoc);
            }
            catch (Exception ex)
            {
                wHelper.Close(oDoc);
            }
        }
Ejemplo n.º 7
0
        private void experiment3ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            object readOnly = true;
            object visible  = true;
            object fileName = "C:" + (char)92 + "Latest Projects" + (char)92 + "Muniz-Marcaida" + (char)92 + "DC_Machine_Lab" + (char)92 + "Others" + (char)92 + sender + ".docx";
            object missing  = Type.Missing;

            Microsoft.Office.Interop.Word._Document    oDoc  = null;
            Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application()
            {
                Visible = false
            };
            oDoc = oWord.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 visible,
                ref missing, ref missing, ref missing, ref missing);
            oDoc.ActiveWindow.Selection.WholeStory();
            oDoc.ActiveWindow.Selection.Copy();
            IDataObject data = Clipboard.GetDataObject();

            rtfData.Rtf = data.GetData(DataFormats.Rtf).ToString();
            oWord.Quit(ref missing, ref missing, ref missing);

            lblExpTitle.Text = sender.ToString();
            pnlE3.Enabled    = false;
            pnlE3.Visible    = false;
            pnlE4.Enabled    = true;
            pnlE4.Visible    = true;
        }
Ejemplo n.º 8
0
        ///<summary>
        /// 替换word模板文件内容,包括表格中内容
        /// </summary>
        /// <param name="filePath">文件全路径</param>
        /// <param name="arr_Old">占位符数组</param>
        /// <param name="arr_New">替换字符串数组</param>
        public Microsoft.Office.Interop.Word.Application WordStringsReplace(string filePath, ArrayList arr_Old, ArrayList arr_New)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            object oMissing = System.Reflection.Missing.Value;
            object file     = filePath;

            Microsoft.Office.Interop.Word._Document doc = app.Documents.Open(ref file,
                                                                             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);
            for (int i = 0; i < arr_Old.Count; i++)
            {
                app.Selection.Find.ClearFormatting();
                app.Selection.Find.Replacement.ClearFormatting();
                app.Selection.Find.Text             = arr_Old[i].ToString();
                app.Selection.Find.Replacement.Text = arr_New[i].ToString();
                object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
                app.Selection.Find.Execute(ref oMissing, ref oMissing, ref oMissing,
                                           ref oMissing, ref oMissing, ref oMissing,
                                           ref oMissing, ref oMissing, ref oMissing,
                                           ref oMissing, ref objReplace, ref oMissing,
                                           ref oMissing, ref oMissing, ref oMissing);
            }

            //保存
            doc.Save();
            doc.Close(ref oMissing, ref oMissing, ref oMissing);
            app.Quit(ref oMissing, ref oMissing, ref oMissing);
            return(app);
        }
Ejemplo n.º 9
0
 private void primeMoverAndTorqueMeasurementToolStripMenuItem_Click(object sender, EventArgs e)
 {
     using (OpenFileDialog ofd = new OpenFileDialog()
     {
         ValidateNames = true, Multiselect = false, Filter = "Word Document|*.docx|Word 97 - 2003 Document|*.doc"
     })
     {
         if (ofd.ShowDialog() == DialogResult.OK)
         {
             object readOnly    = true;
             object visible     = true;
             object save        = false;
             object fileName    = ofd.FileName;
             object missing     = Type.Missing;
             object newTemplate = false;
             object docType     = 0;
             Microsoft.Office.Interop.Word._Document    oDoc  = null;
             Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application()
             {
                 Visible = false
             };
             oDoc = oWord.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 visible,
                 ref missing, ref missing, ref missing, ref missing);
             oDoc.ActiveWindow.Selection.WholeStory();
             oDoc.ActiveWindow.Selection.Copy();
             IDataObject data = Clipboard.GetDataObject();
             rtfData.Rtf = data.GetData(DataFormats.Rtf).ToString();
             oWord.Quit(ref missing, ref missing, ref missing);
             lblExpTitle.Text = fileName.ToString();
         }
     }
 }
Ejemplo n.º 10
0
        private static string RevisarOrtografia(string texto)
        {
            var    app       = new Microsoft.Office.Interop.Word.Application();
            string corregido = string.Empty;

            if (!String.IsNullOrEmpty(texto))
            {
                app.Visible = false;
                object template     = Missing.Value;
                object newTemplate  = Missing.Value;
                object documentType = Missing.Value;
                object visible      = false;

                Microsoft.Office.Interop.Word._Document doc1 = app.Documents.Add(ref template, ref newTemplate,
                                                                                 ref documentType, ref visible);
                doc1.Words.First.InsertBefore(texto);
                object optional = Missing.Value;
                doc1.CheckSpelling(
                    ref optional, ref optional, ref optional, ref optional, ref optional, ref optional,
                    ref optional, ref optional, ref optional, ref optional, ref optional, ref optional);

                object first = 0;
                object last  = doc1.Characters.Count - 1;
                corregido = doc1.Range(ref first, ref last).Text;
            }
            object saveChanges    = false;
            object originalFormat = Missing.Value;
            object routeDocument  = Missing.Value;

            app.Application.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
            return(corregido);
        }
Ejemplo n.º 11
0
        private void ReadWord(string path, string groupID)
        {
            if (IsWork())
            {
                return;
            }
            _work = true;
            _syncContext.Post(PostLabelText, new TextPostData(lab_status, "載入中"));
            _syncContext.Post(PostProcess, 5);

            _app         = new Microsoft.Office.Interop.Word.Application();
            _app.Visible = false;
            _syncContext.Post(PostProcess, 25);

            object unknow = Type.Missing;
            object file   = path;

            _doc = _app.Documents.Open(ref file,
                                       ref unknow, ref unknow, ref unknow, ref unknow,
                                       ref unknow, ref unknow, ref unknow, ref unknow,
                                       ref unknow, ref unknow, ref unknow, ref unknow,
                                       ref unknow, ref unknow, ref unknow);
            _syncContext.Post(PostProcess, 50);

            string content = _doc.Content.Text;

            CloseDoc();

            _datas.Add(new WordData(content, groupID));

            _syncContext.Post(PostProcess, 100);
            _syncContext.Post(PostLabelText, new TextPostData(lab_status, "已完成"));
            _work = false;
        }
Ejemplo n.º 12
0
 private WordApplication()
 {
     this.m_WordApp = new Microsoft.Office.Interop.Word.Application();
     this.m_WordApp.Visible = false;
     this.m_Documents = this.m_WordApp.Documents;
     this.m_Document = this.m_Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oTrue);
     this.m_WordSuggestionList = new List<string>();
 }
Ejemplo n.º 13
0
 private WordApplication()
 {
     this.m_WordApp            = new Microsoft.Office.Interop.Word.Application();
     this.m_WordApp.Visible    = false;
     this.m_Documents          = this.m_WordApp.Documents;
     this.m_Document           = this.m_Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oTrue);
     this.m_WordSuggestionList = new List <string>();
 }
Ejemplo n.º 14
0
        /// <summary>
        /// A function that merges Microsoft Word Documents that uses a template specified by the user
        /// </summary>
        /// <param name="filesToMerge">An array of files that we want to merge</param>
        /// <param name="outputFilename">The filename of the merged document</param>
        /// <param name="insertPageBreaks">Set to true if you want to have page breaks inserted after each document</param>
        /// <param name="documentTemplate">The word document you want to use to serve as the template</param>
        private void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate)
        {
            object defaultTemplate = documentTemplate;
            object missing         = System.Type.Missing;
            object pageBreak       = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;
            object outputFile      = outputFilename;

            // Create  a new Word application
            Microsoft.Office.Interop.Word._Application wordApplication = new Microsoft.Office.Interop.Word.Application();
            if (filesToMerge.Count() == 1)
            {
                pageBreak = false;
            }
            try
            {
                // Create a new file based on our template
                Microsoft.Office.Interop.Word._Document wordDocument = wordApplication.Documents.Add(ref defaultTemplate, ref missing, ref missing, ref missing);

                // Make a Word selection object.
                Microsoft.Office.Interop.Word.Selection selection = wordApplication.Selection;

                int index = 0;

                // Loop thru each of the Word documents
                foreach (string file in filesToMerge)
                {
                    // Insert the files to our template
                    selection.InsertFile(file, ref missing, ref missing, ref missing, ref missing);

                    //Do we want page breaks added after each documents?
                    if (insertPageBreaks && index != filesToMerge.Count() - 1)
                    {
                        selection.InsertBreak(ref pageBreak);
                    }

                    index++;
                }

                // Save the document to it's output file.
                wordDocument.SaveAs(ref outputFile, 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);

                // Clean up!
                wordDocument.Close(ref missing, ref missing, ref missing);
                wordDocument = null;
            }
            catch (Exception ex)
            {
                //I didn't include a default error handler so i'm just throwing the error
                throw ex;
            }
            finally
            {
                // Finally, Close our Word application
                wordApplication.Quit(ref missing, ref missing, ref missing);
            }
        }
Ejemplo n.º 15
0
        void SetWordDocumentPropertyValue(Microsoft.Office.Interop.Word._Document document, string propertyName, string propertyValue)
        {
            object builtInProperties     = document.BuiltInDocumentProperties;
            Type   builtInPropertiesType = builtInProperties.GetType();
            object property     = builtInPropertiesType.InvokeMember("Item", System.Reflection.BindingFlags.GetProperty, null, builtInProperties, new object[] { propertyName });
            Type   propertyType = property.GetType();

            propertyType.InvokeMember("Value", BindingFlags.SetProperty, null, property, new object[] { propertyValue });
        }
Ejemplo n.º 16
0
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            Process[] proc = Process.GetProcessesByName("WINWORD");
            foreach (Process proc1 in proc)
            {
                proc1.Kill();
            }
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

            int errors = 0;

            if (syntaxRichTextBox1.Text.Length > 0)
            {
                app.Visible = true;

                // Setting these variables is comparable to passing null to the function.
                // This is necessary because the C# null cannot be passed by reference.
                object template     = Missing.Value;
                object newTemplate  = Missing.Value;
                object documentType = Missing.Value;
                object visible      = true;

                Microsoft.Office.Interop.Word._Document doc1 = app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);
                doc1.Words.First.InsertBefore(syntaxRichTextBox1.Text);
                Microsoft.Office.Interop.Word.ProofreadingErrors spellErrorsColl = doc1.SpellingErrors;
                errors = spellErrorsColl.Count;

                object optional = Missing.Value;

                doc1.CheckSpelling(
                    ref optional, ref optional, ref optional, ref optional, ref optional, ref optional,
                    ref optional, ref optional, ref optional, ref optional, ref optional, ref optional);

                toolStripLabelStatus.Text = errors + " errors corrected ";
                object first = 0;
                object last  = doc1.Characters.Count - 1;
                syntaxRichTextBox1.Text = doc1.Range(ref first, ref last).Text.Replace("\r", "\r\n");
                //doc1.Close(ref optional, ref optional, ref optional);
                //doc1 = null;
            }

            object saveChanges    = false;
            object originalFormat = Missing.Value;
            object routeDocument  = Missing.Value;

            app.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
            //app.Quit();
            app = null;

            //app.Quit(ref originalFormat, ref originalFormat, ref originalFormat);
            Process[] proc3 = Process.GetProcessesByName("WINWORD");
            foreach (Process proc4 in proc3)
            {
                proc4.Kill();
            }
        }
Ejemplo n.º 17
0
        public bool saveFile(String path, ContainerResult result, ContainerFunction containerFunction, Parametrs option)
        {
            createDocument(containerFunction, result, option);

            _template.SaveAs(FileName: path);
            _template.Close();
            _template = null;

            return true;
        }
Ejemplo n.º 18
0
    private string GetActivePrinter(Microsoft.Office.Interop.Word._Document doc)
    {
        string activePrinter = doc.Application.ActivePrinter;
        int    onIndex       = activePrinter.LastIndexOf(" on ");

        if (onIndex >= 0)
        {
            activePrinter = activePrinter.Substring(0, onIndex);
        }
        return(activePrinter);
    }
Ejemplo n.º 19
0
        public static void PrintWordDot(string lv模板文件名, List <string> lv模板词汇, List <string> lv替换词汇)
        {
            object   path;       //文件路径
            string   strContent; //文件内容
            string   lvssss = Application.StartupPath + "\\Microsoft.Office.Interop.Word.dll";
            Assembly ass;
            string   lv模板文件名含路径 = Application.StartupPath + "\\" + lv模板文件名;
            Object   oMissing   = System.Reflection.Missing.Value;
            object   obj模板      = oMissing;
            object   obj;

            //获取并加载DLL类库中的程序集
            ass = Assembly.LoadFile(lvssss);

            obj = ass.CreateInstance("Microsoft.Office.Interop.Word.ApplicationClass");
            //获取类的类型:必须使用名称空间+类名称
            Microsoft.Office.Interop.Word._Application WordApp = obj as Microsoft.Office.Interop.Word._Application;
            WordApp.Visible = true;
            try
            {
                Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Add(ref obj模板, ref oMissing, ref oMissing, ref oMissing);
                object FindText, ReplaceWith, Replace;
                for (int lvi = 0; lvi < lv模板词汇.Count; lvi++)
                {
                    WordDoc.Content.Find.Text = lv模板词汇[lvi];
                    //要查找的文本
                    FindText = lv模板词汇[lvi];
                    //替换文本
                    //ReplaceWith = strNewText;
                    ReplaceWith = lv替换词汇[lvi];

                    //wdReplaceAll - 替换找到的所有项。
                    //wdReplaceNone - 不替换找到的任何项。
                    //wdReplaceOne - 替换找到的第一项。
                    Replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;


                    //移除Find的搜索文本和段落格式设置
                    WordDoc.Content.Find.ClearFormatting();
                    WordDoc.Content.Find.Execute(ref FindText, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref ReplaceWith, ref Replace, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                }
                WordDoc.PrintPreview();
                WordDoc.Saved = true;
                //关闭wordDoc文档
                WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                //关闭wordApp组件对象
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
            }
            catch //(Exception ex)
            {
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                throw;
            }
        }
Ejemplo n.º 20
0
        public static void PrintWord(object FileName, string ConnectionString, string coTitle, string sFontName, string Lang, string where,
                                     string where1, string where2, string where3, string where4, string where5, string where6, string where7, string where8,
                                     string where9, string where10, string User)
        {
            object oMissing = Missing.Value;

            Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Documents   oDocs = oWord.Documents;
            Microsoft.Office.Interop.Word._Document   oDoc  = null;

            System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            try
            {
                oDoc = oDocs.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);
                oWord.Visible = true;

                //Cap nhat properties
                SetProperty(oDoc, "ConnectionString", ConnectionString);
                SetProperty(oDoc, "CoTitle", coTitle);
                SetProperty(oDoc, "sFontName", sFontName);
                SetProperty(oDoc, "Lang", Lang);
                SetProperty(oDoc, "where", where);
                SetProperty(oDoc, "where1", where1);
                SetProperty(oDoc, "where2", where2);
                SetProperty(oDoc, "where3", where3);
                SetProperty(oDoc, "where4", where4);
                SetProperty(oDoc, "where5", where5);
                SetProperty(oDoc, "where6", where6);
                SetProperty(oDoc, "where7", where7);
                SetProperty(oDoc, "where8", where8);
                SetProperty(oDoc, "where9", where9);
                SetProperty(oDoc, "where10", where10);
                SetProperty(oDoc, "User", User);

                try
                {
                    RunMacro(oWord, new object[] { "CreatReport" });
                }
                catch {}
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "Error!");
            }
            finally
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oDocs);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
                GC.Collect();
            }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// 向Word书签的位置插入表格
 /// </summary>
 /// <param name="odoc"></param>
 /// <param name="bookmark"></param>
 /// <param name="oMissing"></param>
 /// <returns></returns>
 public Microsoft.Office.Interop.Word.Table AddTableToWord(Microsoft.Office.Interop.Word._Document odoc, ref Microsoft.Office.Interop.Word.Range wrdRng, object bookmark, ref object oMissing, int row, int col, int space)
 {
     Microsoft.Office.Interop.Word.Table oTable;
     wrdRng = odoc.Bookmarks.get_Item(ref bookmark).Range;
     oTable = odoc.Tables.Add(wrdRng, row, col, ref oMissing, ref oMissing);
     oTable.Range.ParagraphFormat.SpaceAfter = space;
     //设置表格样式
     oTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
     oTable.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
     return(oTable);
 }
Ejemplo n.º 22
0
        private void CloseDoc()
        {
            if (_doc != null)
            {
                _doc.Close();
                _doc = null;
            }

            if (_app != null)
            {
                _app.Quit();
                _app = null;
            }
        }
Ejemplo n.º 23
0
        public static void SetProperty(Microsoft.Office.Interop.Word._Document oDoc, string Item, string Value)
        {
            object oCustomProps    = oDoc.CustomDocumentProperties;
            object oBuiltInPro     = oDoc.BuiltInDocumentProperties;
            Type   typeCustomProps = oBuiltInPro.GetType();

            try
            {
                typeCustomProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null, oCustomProps, new object[] { Item, Value });
            }
            catch
            {
            }
        }
Ejemplo n.º 24
0
 /// <summary>
 /// word中创建一个段落
 /// </summary>
 /// <param name="odoc"></param>
 /// <param name="bookmark">书签</param>
 /// <param name="oRng">书签位置</param>
 /// <param name="text">显示文本</param>
 /// <param name="blod">加粗</param>
 /// <param name="spaceafter">段间间隔</param>
 /// <param name="aliment">对齐方式</param>
 public void CreatParagraph(Microsoft.Office.Interop.Word._Document odoc, object bookmark, ref object oRng, string text, int blod, int spaceafter, Microsoft.Office.Interop.Word.WdParagraphAlignment aliment)
 {
     Microsoft.Office.Interop.Word.Paragraph oPara;
     if (bookmark != null)
     {
         oRng = odoc.Bookmarks.get_Item(ref bookmark).Range;
     }
     oPara                   = odoc.Content.Paragraphs.Add(ref oRng);
     oPara.Range.Text        = text;
     oPara.Range.Font.Bold   = blod;
     oPara.Format.SpaceAfter = spaceafter;
     oPara.Alignment         = aliment;
     oPara.Range.InsertParagraphAfter();
 }
Ejemplo n.º 25
0
 /// <summary>
 /// 文件打开
 /// </summary>
 /// <param name="filename"></param>
 public void OpenWord(object filename)
 {
     try
     {
         oWord.Visible = true;
         oDoc          = oWord.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);
     }
     catch (Exception)
     {
         return;
     }
 }
Ejemplo n.º 26
0
        //Загрузка содержимого Word файла
        private void LoadDocx(string filename)
        {
            richTextBox.Document = new FlowDocument();
            Microsoft.Office.Interop.Word.Application wordObject = new Microsoft.Office.Interop.Word.Application();
            object File       = EXE_DIRECTORY + FOLDER + filename;
            object nullobject = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Application wordobject = new Microsoft.Office.Interop.Word.Application();
            wordobject.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
            Microsoft.Office.Interop.Word._Document docs = wordObject.Documents.Open(ref File);
            docs.ActiveWindow.Selection.WholeStory();
            docs.ActiveWindow.Selection.Copy();
            richTextBox.Paste();
            docs.Close();
        }
Ejemplo n.º 27
0
        private void WriteWord(string filepath, string path, string content)
        {
            _app = new Microsoft.Office.Interop.Word.Application();
            _doc = _app.Documents.Open(filepath);

            _doc.Paragraphs.Last.Range.Font.Name = "新明細體";
            _doc.Paragraphs.Last.Range.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 0;
            _doc.Paragraphs.Last.Range.Text = content;


            Object Nothing     = System.Reflection.Missing.Value;
            object objWordName = path;

            _doc.SaveAs(ref objWordName, 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);
            CloseDoc();
        }
Ejemplo n.º 28
0
        /// <summary>
        /// 向Word书签的位置插入图片
        /// </summary>
        /// <param name="odoc"></param>
        /// <param name="bookmark">书签</param>
        /// <param name="picturePath">图片路径</param>
        /// <param name="width">图片宽度设定</param>
        /// <param name="hight">图片高度设定</param>
        public void AddPictureToWord(Microsoft.Office.Interop.Word._Document odoc, object bookmark, string picturePath, float width, float hight)
        {
            if (!File.Exists(picturePath))
            {
                return;
            }

            Microsoft.Office.Interop.Word.InlineShape oShape;
            Microsoft.Office.Interop.Word.Range       imageRng = odoc.Bookmarks.get_Item(ref bookmark).Range;
            object LinkToFile       = false;
            object SaveWithDocument = true;
            object range            = imageRng;

            oShape        = imageRng.InlineShapes.AddPicture(picturePath, ref LinkToFile, ref SaveWithDocument, ref range);
            oShape.Width  = width; //图片宽度
            oShape.Height = hight; //图片高度
        }
Ejemplo n.º 29
0
        /// PrinPreview the document
        /// </summary>
        /// <param name="fileToPrint"></param>
        private void PrinPriview(string fileToPrint)
        {
            object missing         = System.Type.Missing;
            object objFile         = fileToPrint;
            object readOnly        = true;
            object addToRecentOpen = false;

            // Create  a new Word application
            Microsoft.Office.Interop.Word._Application wordApplication = new Microsoft.Office.Interop.Word.Application();
            try
            {
                // Create a new file based on our template
                Microsoft.Office.Interop.Word._Document wordDocument = wordApplication.Documents.Open(ref objFile, ref missing, ref readOnly, ref addToRecentOpen);

                wordApplication.Options.SaveNormalPrompt = false;

                if (wordDocument != null)
                {
                    // Show print preview
                    wordApplication.Visible = true;
                    wordDocument.PrintPreview();
                    wordDocument.Activate();
                    //wordDocument.op
                    while (!_IsPringPriview)
                    {
                        wordDocument.ActiveWindow.View.Magnifier = true;
                        Thread.Sleep(500);
                    }

                    wordDocument.Close(ref missing, ref missing, ref missing);
                    wordDocument = null;
                }
            }
            catch
            {
                //I didn't include a default error handler so i'm just throwing the error
                // throw ex;
            }
            finally
            {
                // Finally, Close our Word application
                wordApplication.Quit(ref missing, ref missing, ref missing);
                wordApplication = null;
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// 导出word功能
        /// </summary>
        /// <param name="sender">事件对象</param>
        /// <param name="e">事件参数</param>
        private void t_tsb_ExportWord_Click(object sender, RoutedEventArgs e)
        {
            object oMissing = System.Reflection.Missing.Value;

            //创建一个Word应用程序实例
            Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application();
            //设置为不可见
            oWord.Visible = false;
            //模板文件地址,这里假设在X盘根目录
            object oTemplate = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\Template\\Template.doc";

            //以模板为基础生成文档
            Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);
            //声明书签数组
            object[] oBookMark = new object[4];
            //赋值书签名
            oBookMark[0] = "Company_Name";
            oBookMark[1] = "Tel";
            oBookMark[2] = "Email";
            oBookMark[3] = "Fax";
            //赋值任意数据到书签的位置
            oDoc.Bookmarks.get_Item(ref oBookMark[0]).Range.Text = PTBQuotation.Company_Name;
            oDoc.Bookmarks.get_Item(ref oBookMark[1]).Range.Text = PTBQuotation.Tel;
            oDoc.Bookmarks.get_Item(ref oBookMark[2]).Range.Text = PTBQuotation.Email;
            oDoc.Bookmarks.get_Item(ref oBookMark[3]).Range.Text = PTBQuotation.Fax;
            //弹出保存文件对话框,保存生成的Word
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter     = "Word Document(*.doc)|*.doc";
            sfd.DefaultExt = "Word Document(*.doc)|*.doc";
            if (sfd.ShowDialog() == true)
            {
                object filename = sfd.FileName;

                oDoc.SaveAs(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);
                oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                //关闭word
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);

                System.Diagnostics.Process.Start(sfd.FileName);
            }
        }
Ejemplo n.º 31
0
    static void Main()
    {
        Console.WriteLine("Enter a string to spell-check:");
        string stringToSpellCheck = Console.ReadLine();
        string spellingResults;
        int    errors = 0;

        if (stringToSpellCheck.Length == 0)
        {
            spellingResults = "No string to check";
        }
        else
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Console.WriteLine("\nChecking the string for misspellings ...");
            app.Visible = false;

            Microsoft.Office.Interop.Word._Document tempDoc = app.Documents.Add();

            tempDoc.Words.First.InsertBefore(stringToSpellCheck);
            Microsoft.Office.Interop.Word.ProofreadingErrors spellErrorsColl = tempDoc.SpellingErrors;
            errors = spellErrorsColl.Count;

            // 1. Without using optional parameters
            // object ignoreCase    = true;
            // object alwaysSuggest = false;
            // object optional      = Missing.Value;
            // tempDoc.CheckSpelling( ref optional, ref ignoreCase, ref alwaysSuggest,
            //     ref optional, ref optional, ref optional, ref optional, ref optional,
            //     ref optional, ref optional, ref optional, ref optional );

            //2. Using the "omit ref" feature
            object optional = Missing.Value;
            tempDoc.CheckSpelling(optional, true, false, optional, optional, optional, optional, optional, optional, optional, optional, optional);

            //3. Using "omit ref" and optional parameters tempDoc.CheckSpelling( Missing.Value, true, false );
            app.Quit(false);
            spellingResults = errors + " errors found";
        }

        Console.WriteLine(spellingResults);
        Console.WriteLine("\nPress <Enter> to exit program.");
        Console.ReadLine();
    }
Ejemplo n.º 32
0
        string GetTextFromWordFile(string path)
        {
            Office.Word._Application appWord = null;
            Office.Word._Document    docWord = null;

            Object filename              = path;
            Object ConfirmConversions    = Missing.Value;
            Object ReadOnly              = true;
            Object AddToRecentFiles      = Missing.Value;
            Object PasswordDocument      = Missing.Value;
            Object PasswordTemplate      = Missing.Value;
            Object Revert                = Missing.Value;
            Object WritePasswordDocument = Missing.Value;
            Object WritePasswordTemplate = Missing.Value;
            Object Format                = Missing.Value;
            Object Encoding              = Missing.Value;
            Object Visible               = false;

            Object saveChanges    = false;
            Object originalFormat = null;
            Object routeDoc       = null;

            appWord         = new Office.Word.Application();
            appWord.Visible = false;
            docWord         = appWord.Documents.Open2000(ref filename, ref ConfirmConversions, ref ReadOnly,
                                                         ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
                                                         ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate,
                                                         ref Format, ref Encoding, ref Visible);
            if (docWord.ProtectionType == Office.Word.WdProtectionType.wdNoProtection)
            {
                docWord.ActiveWindow.Selection.WholeStory();
                docWord.ActiveWindow.Selection.Copy();
                GetClipboardContent();
            }
            else
            {
                curr_clpbrd_content = "";
            }
            appWord.ActiveDocument.Close(ref saveChanges, ref originalFormat, ref routeDoc);
            appWord.Quit(ref saveChanges, ref originalFormat, ref routeDoc);


            return(curr_clpbrd_content);
        }
Ejemplo n.º 33
0
        private void createDocument(ContainerFunction function, ContainerResult result, Parametrs option )
        {
            _template = _oWord.Documents.Add(Environment.CurrentDirectory + _directoryTemplate);
            Char[] chr = { CHAR_SPACE, CHAR_PLUS, CHAR_COMMA };
            String stroke = "";

            _template.Bookmarks[MARK_COUNT_GENERATION].Range.Text = option.countGeneration.ToString();
            _template.Bookmarks[MARK_CHANCE_MUTATION].Range.Text = option.сhanceMutation.ToString();
            _template.Bookmarks[MARK_COUNT_POPULATE].Range.Text = option.countPopulate.ToString();
            _template.Bookmarks[MARK_VALUE_MUTATION].Range.Text = option.valueMutation.ToString();
            _template.Bookmarks[MARK_TURN_INTEGER].Range.Text = option.turnInteger;
            _template.Bookmarks[MARK_TIME].Range.Text = result.time.ToString();

            if (result != null)
            {

                String vectorResult = "";
                String realResult = "";
                String realRestrict = "";

                int i = 1;
                foreach (int vect in result.vector)
                {
                    vectorResult += X + i.ToString() + SIGN_EQUALLY + vect + SIGN_COMMA + SIGN_SPACE + SIGN_SPACE;
                    i++;
                }

                stroke = vectorResult.Trim().Trim(chr);

                _template.Bookmarks[MARK_VECTOR_RESULT].Range.Text = stroke;

                realResult = result.realResult.ToString();

                _template.Bookmarks[MARK_REAL_RESULT].Range.Text = realResult;

                foreach (int vect in result.realRestrict)
                {
                    realRestrict += vect.ToString() + SIGN_COMMA + SIGN_SPACE + SIGN_SPACE + SIGN_SPACE;

                }

                stroke = realRestrict.Trim().Trim(chr) + SIGN_SPACE;

                _template.Bookmarks[MARK_REAL_RESTRICT].Range.Text = stroke;

            }

            if (function != null)
            {
                String line = "";
                foreach (MatrixItem matrix in function.matrix)
                {
                    line = "" ;
                    int i = 1;
                    foreach (Double vect in matrix.items)
                    {

                        double num;

                        if (vect < 0)
                        {
                            line += SIGN_MINUS + SIGN_SPACE;
                            num = Math.Abs(vect);
                        }
                        else
                        {
                            num = vect;
                            line += SIGN_PLUS + SIGN_SPACE;
                        }

                        line += num.ToString() + X + i + SIGN_SPACE;

                        i++;
                    }

                    stroke = line.Trim().Trim(chr);
                    stroke += matrix.Sign;
                    stroke += SIGN_SPACE;

                    stroke += matrix.restriction.ToString();
                    _template.Bookmarks[MARK_FUNCTION_RESTRICT].Range.Text = stroke + Environment.NewLine;
                }

                String lineFunc = "";

                foreach (Double vect in function.fitness)
                {

                    double num;

                    if (vect < 0)
                    {
                        lineFunc += SIGN_MINUS + SIGN_SPACE;
                        num = Math.Abs(vect);
                    }
                    else
                    {
                        num = vect;
                        lineFunc += SIGN_PLUS + SIGN_SPACE;
                    }

                    lineFunc += num.ToString() + SIGN_SPACE;

                }

                stroke = lineFunc.Trim().Trim(chr) + function.cursor + SIGN_SPACE;
                _template.Bookmarks[MARK_FUNCTION].Range.Text = stroke;

            }
        }
Ejemplo n.º 34
0
 public void ClearCurrentDocument()
 {
     this.m_WordApp.Documents.Close(ref oFalse, ref oMissing, ref oMissing);
     this.m_Document = this.m_Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oTrue);
 }
Ejemplo n.º 35
0
 public void OpenNewWordFileToEdit()
 {
     oDoc = oWord.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
 }
Ejemplo n.º 36
0
        public bool CloseDocument()
        {
            try
            {
                object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
                oDoc.Close(ref doNotSaveChanges, ref Nothing, ref Nothing);
                oDoc = null;
                return true;

            }
            catch ( Exception )
            {
                return false;
            }
        }
Ejemplo n.º 37
0
 private void openFile(string newFilename)
 {
     oWord = new Microsoft.Office.Interop.Word.Application();
     oWord.Visible = false;
     oDoc = oWord.Documents.Open(newFilename, ReadOnly: false, Visible: true);
 }
Ejemplo n.º 38
0
        public bool Open(string filePath, bool isVisible)
        {
            try
            {
                oWord.Visible = isVisible;

                object path = filePath;
                oDoc = oWord.Documents.Open(ref path,
                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);

                return true;
            }
            catch ( Exception )
            {
                return false;
            }
        }
Ejemplo n.º 39
0
        public bool Quit()
        {
            try
            {
                object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
                oWord.Quit(ref saveOption, ref Nothing, ref Nothing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
                oWord = null;
                oDoc = null;
                odoc = null;
                GC.Collect();

                return true;
            }
            catch ( Exception )
            {
                return false;
            }
        }