Пример #1
0
        public void findAndReplace(Microsoft.Office.Interop.Word.Range a, object findText, object replaceWithText)
        {
            //options
            object matchCase         = false;
            object matchWholeWord    = true;
            object matchWildCards    = false;
            object matchSoundsLike   = false;
            object matchAllWordForms = false;
            object forward           = true;
            object format            = false;
            object matchKashida      = false;
            object matchDiacritics   = false;
            object matchAlefHamza    = false;
            object matchControl      = false;
            object read_only         = false;
            object visible           = true;
            object replace           = 1;
            object wrap    = 1;
            object missing = System.Reflection.Missing.Value;
            //object replaceAll = .WdReplace.wdReplaceAll;
            object replaceOnce = Microsoft.Office.Interop.Word.WdReplace.wdReplaceOne;

            a.Find.Execute(ref findText, ref missing, ref missing, ref missing, ref missing,
                           ref missing, ref missing, ref missing, ref missing, ref replaceWithText,
                           ref replaceOnce, ref missing, ref missing, ref missing, ref missing);
        }
Пример #2
0
        /// <summary>
        /// 发送整个文档内容到指定接口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void sendBtn_Click(object sender, RibbonControlEventArgs e)
        {
            ////获取当前文档的内容
            Microsoft.Office.Interop.Word.Range _rng = Globals.ThisAddIn.Application.ActiveDocument.Content;
            string _curRangeText = _rng.Text;

            string _jsonParam = "{\"document\":\"" + _curRangeText + "\"}";

            string _requesUrl = ConfigurationManager.AppSettings["RequestDocumentUrl"];

            try
            {
                //// 异步等待请求WebAPI
                var hwr = await HttpTool.RequesPostAsync(_requesUrl, _jsonParam);

                HttpTool.ResponseResult _curResult = HttpTool.GetResponseJson <HttpTool.ResponseResult>(hwr);

                if (_curResult.Code == 2000)
                {
                    MessageBox.Show("远程保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show(_curResult.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("发送整个文档内容出错:" + ex.Message);
            }
        }
Пример #3
0
        public void Render(Microsoft.Office.Interop.Word.Table table)
        {
            table.Borders.InsideLineStyle  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            table.Range.Font.Name          = "Calibri";

            // 填入表格資料
            int rowIndex = 1;

            foreach (DataRow row in MyDataTable.Rows)
            {
                ////table.Cell(rowIndex, 1).Range.Font.Bold = 1;
                ////table.Cell(rowIndex, 1).Range.Text = string.Format("{0}{1}({2})",
                ////    row["Project"].ToString(),
                ////    Environment.NewLine,
                ////    row["Skus"].ToString());

                Microsoft.Office.Interop.Word.Range range = table.Cell(rowIndex, 1).Range;

                Microsoft.Office.Interop.Word.Paragraph p1 = range.Paragraphs.Add(range);
                p1.Range.Font.Bold = 0;
                p1.Range.Font.Size = 10;
                p1.Range.Text      = string.Format("({0})", row["Skus"].ToString());

                Microsoft.Office.Interop.Word.Paragraph p2 = range.Paragraphs.Add(range);
                p2.Range.Font.Bold = 1;
                p2.Range.Font.Size = 12;
                p2.Range.Text      = row["Project"].ToString() + Environment.NewLine;

                rowIndex++;
            }
        }
Пример #4
0
        public void SetRange(string text)
        {
            Object oStart = 0;

            this.m_Range = this.m_WordApp.ActiveDocument.Range(ref oStart, ref oStart);
            this.m_Range.InsertAfter(text);
        }
Пример #5
0
 private void btn_Click(object sender, EventArgs e)
 {
     using (OpenFileDialog ofd = new OpenFileDialog()
     {
         ValidateNames = true, Multiselect = false, Filter = "Word 97-2003|*.doc|Word Document|*.docx"
     })
     {
         if (ofd.ShowDialog() == DialogResult.OK)
         {
             object readOnly    = false;
             object visible     = true;
             object save        = false;
             object fileName    = ofd.FileName;
             object newTemplate = false;
             object docType     = 0;
             object missing     = Type.Missing;
             Microsoft.Office.Interop.Word._Document    document;
             Microsoft.Office.Interop.Word._Application application = new Microsoft.Office.Interop.Word.Application()
             {
                 Visible = false
             };
             document = application.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);
             document.ActiveWindow.Selection.WholeStory();
             document.ActiveWindow.Selection.Copy();
             IDataObject dataObject = Clipboard.GetDataObject();
             rtb.Rtf = dataObject.GetData(DataFormats.Rtf).ToString();
             Microsoft.Office.Interop.Word.Range rng = document.Content;
             text = rng.Text;
             application.Quit(ref missing, ref missing, ref missing);
         }
     }
 }
Пример #6
0
      public void Soglasie()
      {
          var path = (string.Format("{0}\\_шаблоны\\" + "Согласие на обработку персональных данных.dotx", AppDomain.CurrentDomain.BaseDirectory));

          Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application {
              Visible = true
          };
          Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Add(path);  //, ReadOnly: false, Visible: true);
          aDoc.Activate();

          // var vm = DataContext as SendGroupViewModel;

          var db = new ProvodnikContext();

          var p = this.DataContext as PersonViewModel;

          Microsoft.Office.Interop.Word.Range range = aDoc.Content;
          range.Find.ClearFormatting();
          range.Find.Execute(FindText: "{today}", ReplaceWith: DateTime.Today.ToString("dd.MM.yyyy"), Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
          range.Find.Execute(FindText: "{till}", ReplaceWith: DateTime.Today.AddYears(1).ToString("dd.MM.yyyy"), Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
          string passport = $"{p.PaspSeriya} {p.PaspNomer} выдан {p.PaspVidan} {p.VidanDat}";

          range.Find.Execute(FindText: "{passport}", ReplaceWith: passport, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
          range.Find.Execute(FindText: "{fio}", ReplaceWith: p.Fio, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
          range.Find.Execute(FindText: "{addres}", ReplaceWith: p.PaspAdres, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
          range.Find.Execute(FindText: "{till}", ReplaceWith: DateTime.Today.AddYears(1).ToString("dd.MM.yyyy"), Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);


          //string otchetDir = @"C:\_provodnikFTP";
          //aDoc.SaveAs(FileName: otchetDir + @"\Согласие на обработку персональных данных.DOCX");
      }
Пример #7
0
 /// <summary>
 /// 修改敏感词的颜色
 /// </summary>
 public void ChangeWordColor(string wordPath)
 {
     Microsoft.Office.Interop.Word._Application word;
     Microsoft.Office.Interop.Word._Document    document;
     word         = new Microsoft.Office.Interop.Word.Application();
     word.Visible = false;                         //默认位true,打开word文档可见窗口,当为false时,窗口不可见
     document     = word.Documents.Open(wordPath); //打开word
     document.Activate();
     //object findStr = "社交圈"; //待查找的文字
     //foreach (var specialWord in specialWordList)
     //{
     // findStr = specialWord;
     //while (word.Selection.Find.Execute(ref findStr))  //查找文字
     //{
     //change font and format of matched words
     //word.Selection.Font.Name = "Tahoma"; //替换字体
     // word.Selection.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdRed;  //替换颜色
     // }
     //}
     foreach (var specialWord in specialWordList)
     {
         Microsoft.Office.Interop.Word.Range rang = document.Range(word.Selection.Start, word.Selection.End); //从word的开始到结束的范围内查找替换
         ReplaceFont(rang, specialWord);                                                                      //新方法,很好用
     }
     document.Save();                                                                                         //保存更改
     document.Close();                                                                                        //关闭当前打开的文档
     word.Application.Quit();
 }
Пример #8
0
        private string GetMSWordWildCard(Microsoft.Office.Interop.Word.Document doc, string wildCrads)
        {
            Object objMissing = Type.Missing;

            Microsoft.Office.Interop.Word.Range rng = doc.Content;
            rng.Find.ClearFormatting();

            object ofindstop = Microsoft.Office.Interop.Word.WdFindWrap.wdFindStop;

            rng.Application.Selection.Find.Text    = wildCrads;
            rng.Application.Selection.Find.Forward = true;  //even if i keep this n the next 2 lines commented, there is no change

            rng.Application.Selection.Find.MatchWildcards = true;

            rng.Application.Selection.Find.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindStop;

            bool isFound = rng.Application.Selection.Find.Execute(ref objMissing, ref objMissing, ref objMissing,
                                                                  ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
                                                                  ref objMissing, ref objMissing);

            if (isFound)
            {
                return(rng.Application.Selection.Text);
            }
            else
            {
                return(string.Empty);
            }
        }
Пример #9
0
        private void btn_SaveDocument_Click(object sender, RoutedEventArgs e)
        {
            forms.SaveFileDialog save = new forms.SaveFileDialog();

            save.DefaultExt = ".doc";

            if (save.ShowDialog() == forms.DialogResult.OK)
            {
                document_address = save.FileName;
                document.SaveToFile(document_address);

                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
                app.Visible = false;
                Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(document_address);
                Microsoft.Office.Interop.Word.Range    r   = doc.Content;
                r.Find.ClearFormatting();
                r.Find.Execute(FindText: "Evaluation Warning: The document was created with Spire.Doc for .NET.", ReplaceWith: "");
                doc.SaveAs(document_address);

                doc.Close();
                app.Quit();

                MessageBox.Show("Документ успешно сохранен");
            }
        }
Пример #10
0
        public async void NapravleniyaMed(List <PersonShortViewModel> persons)
        {
            try
            {
                // await new ProgressRunner().RunAsync(doAction);
                await new ProgressRunner().RunAsync(
                    new Action <ProgressHandler>((progressChanged) =>
                {
                    progressChanged(1, "Формирование направлений");

                    var path = (string.Format("{0}\\_шаблоны\\" + "Направление мед.dotx", AppDomain.CurrentDomain.BaseDirectory));
                    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application {
                        Visible = false
                    };
                    Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Add(path /*, ReadOnly: false, Visible: true*/);
                    aDoc.Activate();

                    object missing = Missing.Value;
                    object what    = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToLine;
                    object which   = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToLast;


                    Microsoft.Office.Interop.Word.Range baseRange = aDoc.Content;
                    baseRange.Cut();

                    Microsoft.Office.Interop.Word.Range range = null;

                    progressChanged(5);
                    var share = 95.0 / persons.Count;
                    foreach (var p in persons)
                    {
                        if (range != null)    //!firstRow
                        {
                            range = aDoc.GoTo(ref what, ref which, ref missing, ref missing);
                            range.InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak);
                        }

                        range = aDoc.GoTo(ref what, ref which, ref missing, ref missing);

                        range.Paste();

                        range.Find.ClearFormatting();
                        range.Find.Execute(FindText: "{fio}", ReplaceWith: p.Fio, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
                        if (p.BirthDat.HasValue)
                        {
                            range.Find.Execute(FindText: "{birthDat}", ReplaceWith: p.BirthDat.Value.ToString("dd.MM.yyyy"), Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
                        }

                        progressChanged(share);
                    }
                    // string otchetDir = @"C:\_provodnikFTP";
                    //  aDoc.SaveAs(FileName: otchetDir + @"\Согласие на обработку персональных данных.DOCX");
                    wordApp.Visible = true;
                })


                    );
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
Пример #11
0
        private static void SetNormalText(Microsoft.Office.Interop.Word.Range range)
        {
            bool isNormal = false;

            foreach (Microsoft.Office.Interop.Word.Range w in range.Words)
            {
                if (w.Text.Trim() == "(")
                {
                    w.Bold   = 0;
                    isNormal = true;
                }

                if (isNormal)
                {
                    w.Bold = 0;
                }

                if (w.Text.Trim() == ")")
                {
                    w.Bold   = 0;
                    isNormal = false;
                }

                if (w.Text.Trim() == "Normal" || w.Text.Trim() == "Abnormal" ||
                    w.Text.Trim() == "Negative" || w.Text.Trim() == "Positive")
                {
                    w.Bold = 0;
                }
            }
        }
Пример #12
0
 private void button2_Click(object sender, RibbonControlEventArgs e)
 {
     // 所选的字体变大
     Microsoft.Office.Interop.Word.Document Doc = Globals.ThisAddIn.Application.ActiveDocument;
     Microsoft.Office.Interop.Word.Range    rng = Globals.ThisAddIn.Application.Selection.Range;
     rng.Font.Size++;
 }
Пример #13
0
        public static void SaveAsWord(List <Bitmap> images)
        {
            using (SaveFileDialog dialog = new SaveFileDialog())
            {
                dialog.Filter     = "Word File | *.doc";
                dialog.DefaultExt = "doc";
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Microsoft.Office.Interop.Word.Application app;
                    Microsoft.Office.Interop.Word.Document    doc;
                    object miss = System.Reflection.Missing.Value;

                    app         = new Microsoft.Office.Interop.Word.Application();
                    app.Visible = false;

                    doc = app.Documents.Add(ref miss, ref miss, ref miss, ref miss);

                    foreach (var img in images)
                    {
                        object start = doc.Content.End - 1;
                        object end   = doc.Content.End;
                        Microsoft.Office.Interop.Word.Range rng = doc.Range(ref start, ref end);
                        Clipboard.SetDataObject(img, true);
                        rng.Paste();
                    }

                    doc.SaveAs2(dialog.FileName);

                    doc.Close(ref miss, ref miss, ref miss);
                    app.Quit(ref miss, ref miss, ref miss);
                }
            }
        }
        static void Main(string[] args)
        {
            // Create new barcode
            Barcode barcode = new Barcode();

            // Set symbology
            barcode.Symbology = SymbologyType.Codabar;
            // Set value
            barcode.Value = "123456";

            // Add checksum to barcode
            barcode.AddChecksum = true;

            // Create word instance
            Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();

            // Hide word
            appWord.Visible = false;

            // Create missing object
            object mis = System.Reflection.Missing.Value;
            // Template file - change to the appropraite path where you copied input.doc
            object fileInput = @"C:\input.doc";
            // Template file - change to the appropraite path where you copied input.doc
            object fileOutput = @"C:\output.doc";

            // Open document
            Microsoft.Office.Interop.Word.Document docWord = appWord.Documents.Open(ref fileInput, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis);

            // Set bookmark name
            object bookmarkName = "MyBookmark";

            // Get bookmark location
            Microsoft.Office.Interop.Word.Range bookmarkLocation = docWord.Bookmarks.get_Item(ref bookmarkName).Range;

            // Get barcode image
            Bitmap image = (Bitmap)barcode.GetImage();

            // Copy image to the clipboard
            Clipboard.SetDataObject(image);

            // Paste barcode image to the document
            bookmarkLocation.Paste();

            // Save to the new document
            docWord.SaveAs(ref fileOutput, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis, ref mis);

            // We needn't save changes
            object saveChanges = false;

            // Close word application
            appWord.Quit(ref saveChanges, ref mis, ref mis);

            // Release COM object
            System.Runtime.InteropServices.Marshal.ReleaseComObject(appWord);
        }
Пример #15
0
        private void buttonReplace_Click(object sender, EventArgs e)
        {
            var key = int.Parse(listResults.SelectedItems[0].SubItems[0].Text);

            Microsoft.Office.Interop.Word.Range selRng = listResults.SelectedItems.Count != 0 ? _resultMap[key] : null;
            if (selRng != null)
            {
                FinderHelpers.ReplaceText(selRng, tbSearchKey.Text, tbReplaceKey.Text);
            }
        }
Пример #16
0
        public void ReestrPeredachi()
        {
            var vm = DataContext as SendGroupViewModel;

            var db  = new ProvodnikContext();
            var ids = vm.Persons.Select(pp => pp.PersonId);
            var pe  = db.Persons.Where(pp => ids.Contains(pp.Id)).ToList();

            if (pe.Count == 0)
            {
                return;
            }


            var path = (string.Format("{0}\\_шаблоны\\" + "Акт передачи документов.docx", AppDomain.CurrentDomain.BaseDirectory));

            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application {
                Visible = false
            };
            Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(path, ReadOnly: false, Visible: false);
            aDoc.Activate();

            object missing = Missing.Value;

            Microsoft.Office.Interop.Word.Range range = aDoc.Content;
            range.Find.ClearFormatting();

            range.Find.Execute(FindText: "{City}", ReplaceWith: vm.City, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
            range.Find.Execute(FindText: "{Filial}", ReplaceWith: vm.Filial, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
            range.Find.Execute(FindText: "{Sp}", ReplaceWith: vm.Sp, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
            range.Find.Execute(FindText: "{Ochniki}", ReplaceWith: vm.Persons.Count(x => x.UchForma == UchFormaConsts.Ochnaya), Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
            range.Find.Execute(FindText: "{Count}", ReplaceWith: vm.Persons.Count(), Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);

            range.Find.Execute(FindText: "{ВЧ}", ReplaceWith: vm.DepoRod, Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);

            var table = aDoc.Tables[3];
            int iRow  = 2;

            foreach (var p in vm.Persons)
            {
                if (iRow > 2)
                {
                    table.Rows.Add(ref missing);
                }
                table.Cell(iRow, 1).Range.Text = (iRow - 1).ToString() + '.';
                table.Cell(iRow, 2).Range.Text = p.Fio;
                table.Cell(iRow, 3).Range.Text = p.UchForma;
                table.Cell(iRow, 4).Range.Text = "ЕСТЬ";

                iRow++;
            }

            aDoc.SaveAs(FileName: otchetDir + $@"\Акт передачи документов.docx");
            aDoc.Close();
        }
Пример #17
0
 public virtual void ToDocx()
 {
     range = MyWord.GetRangeOfLastCharater();
     range.Text = number + "." + title + "\n";
     range.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevel1;
     range = MyWord.GetRangeOfLastCharater();
     foreach (var item in content)
     {
         item.ToDocx();
     }
 }
Пример #18
0
        private void CreateDocument()
        {
            //Create instance for Word app
            Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

            //Set animation status for Word application
            winword.ShowAnimation = false;

            //Set status for Word application is to be visible or not
            winword.Visible = false;

            //Create missing variable for missing value
            object missing = System.Reflection.Missing.Value;

            //Create new document
            Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            //Add header into document
            foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
            {
                //Get header range and add header details
                Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                headerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
                headerRange.Font.Size = 10;
                headerRange.Text      = "Test Header";
            }

            //Add footer into document
            foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
            {
                //Get footer range and add footer details.
                Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                footerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
                footerRange.Font.Size                 = 10;
                footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                footerRange.Text = "Test Footer";
            }

            //Add text to document
            document.Content.SetRange(0, 0);
            document.Content.Text = "Test 1" + Environment.NewLine + "Test 2";

            //Save document
            object filename = @"C:\Users\Jon\Desktop\test.docx";

            document.SaveAs2(ref filename);
            document.Close(ref missing, ref missing, ref missing);
            document = null;
            winword.Quit(ref missing, ref missing, ref missing);
            winword = null;
            MessageBox.Show("Document created successfully!");
        }
Пример #19
0
 /// <summary>
 ///  Ribbon Button Click Event
 /// </summary>
 void Field_Click(object sender, RibbonControlEventArgs e)
 {
     try
     {
         Microsoft.Office.Interop.Word.Range currentRange = Globals.ThisAddIn.Application.Selection.Range;
         currentRange.Text = (sender as RibbonButton).Label;
     }
     catch (Exception exception)
     {
     }
 }
Пример #20
0
 /// <summary>
 /// Получение Названия дисциплины из ТП
 /// </summary>
 /// <returns></returns>
 public String GetDisciplineName()
 {
     String st = String.Empty;
     range = document.Content;//получаем рабочий диапазон из файла (всё содержимое)
     if (range.Find.Execute("изучения дисциплины:")) //если есть строка "Изучение дис."
     {
         range.Expand(3);//3 - выделение всей строки
         st = range.Text.Remove(0,range.Text.IndexOf(':')+1);
     }
     return st;
 }
Пример #21
0
        private void CreateDocument()
        {
            try
            {
                //Create an instance for word app
                Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

                //Set animation status for word application
                //winword.ShowAnimation = false;

                //Set status for word application is to be visible or not.
                winword.Visible = false;

                //Create a missing variable for missing value
                object missing = System.Reflection.Missing.Value;

                //Create a new document
                Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                //string docType = "";
                //string fileDesc = "";

                //docType = txtDocType.Text;

                //fileDesc = defaultPath + @"\" + txtDocType.Text + "s" + @"\" + userDept + @"\" + docType.Substring(0, 1) + txtDocNo.Text + ".docx";

                SetFileDesc();

                //Add the footers into the document
                foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
                {
                    //Get the footer range and add the footer details.
                    Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    footerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
                    footerRange.Font.Size                 = 10;
                    footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    footerRange.Text = fileDesc;
                }

                object filename = @fileDesc;

                document.SaveAs(ref filename);
                ((Microsoft.Office.Interop.Word._Document)document).Close(ref missing, ref missing, ref missing);
                document = null;
                ((Microsoft.Office.Interop.Word._Application)winword).Quit(ref missing, ref missing, ref missing);
                winword = null;
                MessageBox.Show("Document created successfully!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #22
0
 //Select menu item text in word
 void Field_Click(object sender, RibbonControlEventArgs e)
 {
     try
     {
         Microsoft.Office.Interop.Word.Range currentRange = Globals.ThisAddIn.Application.Selection.Range;
         currentRange.Text = (sender as RibbonButton).Label;
     }
     catch (Exception exception)
     {
         log.Error(friendlyErrorMessage + " Field_Click Details:" + exception.Message, exception);
     }
 }
Пример #23
0
        /// <summary>
        /// Закрытие приложения
        /// </summary>
        public void QuitApplication()
        {
            if (application != null)
            {
                range = null;
                table = null;
                document = null;
                application.Quit();
                application = null;                
            }

        }
        private void ExecutedFind(object sender, ExecutedRoutedEventArgs e)
        {
            var pubinfo = e.Parameter as IUserInformation;

            if ((pubinfo == null) || (pubinfo.Source == null) || (AttachedDocument == null))
            {
                return;
            }

            // if is defined Field then jump directly to it
            if (pubinfo.NavigateToSourceAction != null)
            {
                pubinfo.NavigateToSourceAction.Invoke();
                return;
            }

            //if there is a bookmark with name of the workitem title
            if (!string.IsNullOrEmpty(pubinfo.Source.Id.ToString(CultureInfo.InvariantCulture)) && pubinfo.Source.Id != 0)
            {
                object title = string.Concat("w2t", pubinfo.Source.Id.ToString(CultureInfo.InvariantCulture));

                if (AttachedDocument.Bookmarks.Exists(title.ToString()))
                {
                    AttachedDocument.Bookmarks[title].Select();
                }
                else
                {
                    //if there is no bookmark, but it has an Id -> Find ID!
                    Microsoft.Office.Interop.Word.Range range = AttachedDocument.Range();
                    var find = range.Find;
                    find.Text = pubinfo.Source.Id.ToString(CultureInfo.InvariantCulture);
                    if (find.Execute())
                    {
                        range.Select();
                    }
                }
            }
            else
            {
                //If not propper synced, search for the Title
                Microsoft.Office.Interop.Word.Range range = AttachedDocument.Range();
                var find = range.Find;
                if (!pubinfo.Source.Fields.Contains(FieldReferenceNames.SystemTitle))
                {
                    return;
                }
                find.Text = pubinfo.Source.Fields[FieldReferenceNames.SystemTitle].Value;
                if (find.Execute())
                {
                    range.Select();
                }
            }
        }
Пример #25
0
        public static string GetRangeText(Microsoft.Office.Interop.Word.Range range, bool isIncludeHidenText = true)
        {
            if (range == null)
            {
                return(string.Empty);
            }

            if (isIncludeHidenText)
            {
                range.TextRetrievalMode.IncludeHiddenText = true;
            }

            return(range.Text);
        }
Пример #26
0
        private void btnAnalyze_Click(object sender, EventArgs e)
        {
            try
            {
                string textFromDoc;
                var    app = (Microsoft.Office.Interop.Word._Application)Globals.ThisAddIn.Application;
                //Microsoft.Office.Interop.Word.Document document = this.Application.ActiveDocument;

                var doc = app.Selection.Document;
                textFromDoc = app.Selection.Text;
                doc.Content.Select();
                Microsoft.Office.Interop.Word.Range rng = doc.Content;
                var contents = rng.Text;


                var outFile = @"C:\LanguageTool\statistics.json";
                var inFile  = @"C:\LanguageTool\camText.txt";
                File.WriteAllText(inFile, contents, Encoding.Unicode);
                outFile.DeleteFile();
                Utilities.ScanFile(inFile, outFile);

                var resOutput = File.ReadAllText(outFile);
                //var res = new Statistics();
                //res.Words = resOutput.After("\"Words\":\"").Before("\"");
                res = JsonConvert.DeserializeObject <Statistics>(File.ReadAllText(outFile));


                lblSentences.Text  = res.Sentences;
                lblWords.Text      = res.Words;
                lblConsonants.Text = res.Consonants;
                lblVowels.Text     = res.Vowels;

                lblLongestWord.Text      = res.LongestWord;
                lblLongestWordChars.Text = res.LongestWordChars;

                lblLongestSentence.Text      = res.LongestSentence;
                lblLongestSentenceWords.Text = res.LongestSentenceWords;

                llViewWords.Enabled = true;
                btnAddZwsp.Enabled  = true;
            }
            catch (Exception x)
            {
                XLogger.Error(x);
                MessageBox.Show("Something went wrong");
            }
        }
Пример #27
0
        /// <summary>
        /// The Model for a Crowdproof job.  This creates the View elements for this task
        /// </summary>
        /// <param name="data">The CrowdproofData instance for this job</param>
        /// <param name="jobNumber">The unique job number</param>
        //public HumanMacroJob(HumanMacroData data, int jobNumber)
        //public HumanMacroJob(int jobNumber, Microsoft.Office.Interop.Word.Range range)
        public HumanMacroJob(Microsoft.Office.Interop.Word.Range toShorten, int job, HumanMacroData.Separator separator, double reward, int redundancy, string title, string subtitle, string instructions, HumanMacroData.ReturnType type, HumanMacroData.TestOrReal test)
        {
            //this.data = data;
            this.jobNumber = job;

            Globals.Soylent.jobToDoc[jobNumber] = Globals.Soylent.Application.ActiveDocument;

            this.data = new HumanMacroData(toShorten, job, separator, reward, redundancy, title, subtitle, instructions, type, test);

            HITView hit = Globals.Soylent.soylentMap[Globals.Soylent.Application.ActiveDocument].addHIT(HIT_TYPE, data, jobNumber);

            hit.addStage(1, HITData.ResultType.Macro, data.macroStageData, "Running Macro", 10, 0.10, jobNumber);
            //hit.addStage(2, HITData.ResultType.Fix, "Fix Errors", 5, 0.05);
            //hit.addStage(3, HITData.ResultType.Verify, "Quality Control", 5, 0.05);

            data.startTask();
        }
Пример #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; //图片高度
        }
Пример #29
0
        public static void preencheArquivoWord(String caminhoArquivo, String dsNomeArquivo, String[] dsFindText, String[] dsReplaceWith, Boolean abreVisualizao = false)
        {
            //Somente irá funcionar se o pacote office estiver instalado no computador
            try
            {
                #region 'Inicio'
                object missing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Application oApp = new Microsoft.Office.Interop.Word.Application();
                object template = caminhoArquivo;
                Microsoft.Office.Interop.Word.Document oDoc = oApp.Documents.Add(ref template, ref missing, ref missing, ref missing);

                //Troca o conteúdo de alguns tags
                Microsoft.Office.Interop.Word.Range oRng = oDoc.Range(ref missing, ref missing);
                object MatchWholeWord = true;
                object Forward        = false;
                object replace        = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
                #endregion

                for (int i = 0; i < dsFindText.Length; i++)
                {
                    object FindText    = dsFindText[i];
                    object ReplaceWith = dsReplaceWith[i];

                    oRng.Find.Execute(ref FindText, ref missing, ref MatchWholeWord,
                                      ref missing, ref missing, ref missing, ref Forward,
                                      ref missing, ref missing, ref ReplaceWith, ref replace,
                                      ref missing, ref missing, ref missing, ref missing);
                }

                #region 'Final'
                oApp.Visible = abreVisualizao;
                oDoc.SaveAs2(String.Format("{0}\\{1}", retornaDiretorio(caminhoArquivo), dsNomeArquivo));
                if (abreVisualizao == false)
                {
                    Alert.informacao("Arquivo Exportado.");
                    oDoc.Close();
                    oApp.Quit();
                }
                #endregion
            }
            catch (Exception erro)
            {
                Alert.erro("Erro ao preencher arquivo do Word" + erro.Message);
            }
        }
Пример #30
0
        /// <summary>
        /// 修改文字,修改文字样式
        /// </summary>
        /// <param name="rng"></param>
        /// <param name="findWhat"></param>
        /// <returns></returns>
        public bool ReplaceFont(Microsoft.Office.Interop.Word.Range rng, string findWhat)
        {
            bool hasFound = false;

            rng.Find.ClearFormatting();
            rng.Find.Replacement.ClearFormatting();
            rng.Find.Replacement.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdRed;
            rng.Find.Text             = findWhat; //需要被替换掉的文字
            rng.Find.Replacement.Text = findWhat; //需要替换成的新文字
            rng.Find.Forward          = true;
            rng.Find.Wrap             = Microsoft.Office.Interop.Word.WdFindWrap.wdFindStop;

            //change this property to true as we want to replace format
            rng.Find.Format = true;

            hasFound = rng.Find.Execute(Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
            return(hasFound);
        }
Пример #31
0
        public static int FileGeneration(Bitmap bitmap)
        {
            try
            {
                int returnval = 0;
                Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();
                winword.ShowAnimation = false;
                winword.Visible       = false;
                object missing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
                {
                    Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                    headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    headerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
                    headerRange.Font.Size = 10;
                    headerRange.Text      = "SAMPLE HEADER NAME";
                }


                Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
                object styleHeading1 = "Heading 1";
                para1.Range.set_Style(ref styleHeading1);
                para1.Range.Text = bitmap.ToString();
                para1.Range.InsertParagraphAfter();


                object filename = @"E:\TestFile.docx";
                document.SaveAs2(filename);
                document.Close(ref missing, ref missing, ref missing);
                document = null;
                winword.Quit(ref missing, ref missing, ref missing);
                winword = null;
                MessageBox.Show("Document created successfully !");
                return(returnval);
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #32
0
 /// This Method create table in ms-word document
 public void CreateTable(int Row, int column)
 {
     // create table in word documnet in word application with table reference name tbl1
     Microsoft.Office.Interop.Word.Table tbl1;
     // calculate the range of endofdocu
     Microsoft.Office.Interop.Word.Range wordRange = doc.Bookmarks.get_Item(ref endofdoc).Range;
     // add table with document with number of row and column
     tbl1 = doc.Content.Tables.Add(wordRange, 3, 3, ref objMiss, ref objMiss);
     // set border visibility true by input 1 and false by input 0
     tbl1.Borders.Enable = 1;
     // set text in each cell of table
     for (int r = 1; r <= 3; r++)
     {
         for (int c = 1; c <= 3; c++)
         {
             tbl1.Cell(r, c).Range.Text = "r" + r + "c" + c;
         }
     }
 }
Пример #33
0
        public void CreateFile(string Content, string Path)
        {
            Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

            winword.ShowAnimation = false;
            winword.Visible       = false;

            object missing = System.Reflection.Missing.Value;


            Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
            {
                //Get the header range and add the header details.
                Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                headerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
                headerRange.Font.Size = 22;
                headerRange.Text      = this.Title + "\r\n";
            }

            document.Content.SetRange(0, 0);
            document.Content.Text = Content;

            /*
             * string StartPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
             * string EndingPath = @"\Resources\src\Generated\" + this.Name + ".docx";
             * string FullCurrentProjectPath = StartPath + EndingPath;
             */


            object filename = Path; /*FullCurrentProjectPath;*/

            document.SaveAs2(ref filename);
            document.Close(ref missing, ref missing, ref missing);
            document = null;
            winword.Quit(ref missing, ref missing, ref missing);
            winword = null;
        }
Пример #34
0
 public void ToDocx()
 {
     range = MyWord.GetRangeOfLastCharater();
     range.Text = text + "\n";
     range.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevelBodyText;
 }
Пример #35
0
 public void SetRange(string text)
 {
     Object oStart = 0;
     this.m_Range = this.m_WordApp.ActiveDocument.Range(ref oStart, ref  oStart);
     this.m_Range.InsertAfter(text);
 }
Пример #36
0
        public String GetYearString()
        {
            //2013 года
            String st = String.Empty;
            range = document.Content;
            if (range.Find.Execute("года"))
            {
                range.Expand(3);
                st = range.Text;
            }

            return st;
        }
Пример #37
0
 /// <summary>
 /// Получение специализации из ТП
 /// </summary>
 /// <returns></returns>
 public String GetSpecializationName()
 {
     String st = String.Empty;
     range = document.Content;
     if (range.Find.Execute("по специализации"))
     {
         range.Expand(3);
         st = range.Text;
     }
     if (st!=string.Empty)
      st.Remove(0, "по специализации".Length);
     return st;
 }
Пример #38
0
 /// <summary>
 /// Получение Специальности из ТП
 /// </summary>
 /// <returns></returns>
 public String GetProfessionName()
 {
     String st = String.Empty;
     range = document.Content;
     if (range.Find.Execute("по специальности:"))
     {
         range.Expand(3);
         st = range.Text;
     }
     
     return st.Remove(0,"по специальности:".Length);
 }
Пример #39
0
 public void ToDocx()
 {
     range = MyWord.GetRangeOfLastCharater();
     range.InlineShapes.AddPicture(FileName:imageFileName);
 }