//Metodo generico para adicionar condicao
        public void AddCondicao(string contato, string atributo, string operacao, string comparacao, string resultado)
        {
            Word.Range RangeCondicao = Range;
            RangeCondicao.SetRange(Range.End, Range.End);

            string condicao = string.Format("{0}.{1} {2} \"{3}\"{4}", contato, atributo, operacao, comparacao, resultado);

            RangeCondicao.Select();
            RangeCondicao.Application.Selection.Font.Subscript = 0;
            RangeCondicao.InsertAfter("[");
            RangeCondicao.Start = RangeCondicao.Start + 1;
            RangeCondicao.Select();
            RangeCondicao.InsertAfter(condicao);
            RangeCondicao.End = Range.Start + condicao.Length;
            RangeCondicao.Select();
            RangeCondicao.Application.Selection.Font.Subscript = -1;
            RangeCondicao.SetRange(RangeCondicao.End - resultado.Length, RangeCondicao.End);
            RangeCondicao.Select();
            RangeCondicao.Application.Selection.Font.Subscript = 0;
            RangeCondicao.InsertAfter("]");
            RangeCondicao.Select();
            RangeCondicao.Application.Selection.Font.Subscript = 0;
            RangeCondicao.SetRange(RangeCondicao.End, RangeCondicao.End);
            RangeCondicao.Select();

            Range.SetRange(RangeCondicao.End, RangeCondicao.End);
        }
Beispiel #2
0
 private void InserirTexto(string texto)
 {
     range.InsertAfter(texto);
     range.Select();
     range.Bold           = 0;
     range.Font.Subscript = 0;
     range.SetRange(range.End, range.End);
 }
Beispiel #3
0
        private void SaveCrossReport(object sender, RoutedEventArgs e)
        {
            object missing = System.Reflection.Missing.Value;

            Word.ApplicationClass WordApp = new Word.ApplicationClass();
            Word.Document         doc     = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            Word.Range            range   = doc.Range(0, ref missing);
            SaveFileDialog        dialog  = new SaveFileDialog()
            {
                Filter = "Word Files (*doc)|*.doc;"
            };

            if (dialog.ShowDialog() == true)
            {
                object fileName = dialog.FileName;
                try
                {
                    range.Font.Name = "Georgia";
                    range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    range.Font.Size      = 14.0F;
                    range.Font.Bold      = 1;
                    range.Font.Underline = Word.WdUnderline.wdUnderlineSingle;
                    range.InsertAfter("Перекрестная статистика по художникам\n\n");
                    range.Font.Underline = Word.WdUnderline.wdUnderlineNone;

                    var table = range.Tables.Add(range.Paragraphs[2].Range, CrossView.Table.Rows.Count + 1, CrossView.Table.Columns.Count, ref missing, ref missing);
                    range.Tables[1].Range.Font.Size = 10;
                    range.Tables[1].Range.Font.Name = "Consolas";
                    range.Tables[1].Range.Font.Bold = 0;
                    range.Tables[1].Columns.DistributeWidth();
                    range.Tables[1].Borders.InsideLineStyle  = Word.WdLineStyle.wdLineStyleSingle;
                    range.Tables[1].Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;

                    for (int i = 0; i < CrossView.Table.Columns.Count; i++)
                    {
                        range.Tables[1].Cell(1, i + 1).Range.Text = CrossView.Table.Columns[i].ColumnName;
                    }

                    for (int k = 0; k < CrossView.Table.Rows.Count; k++)
                    {
                        var items = CrossView.Table.Rows[k].ItemArray;
                        for (int i = 0; i < items.Length; i++)
                        {
                            range.Tables[1].Cell(k + 2, i + 1).Range.Text = items[i].ToString();
                        }
                    }
                    range.InsertAfter("\nDate:" + DateTime.Now.ToString());

                    doc.SaveAs2(ref fileName);
                    WordApp.Visible = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Создать отчет не удалось. Ошибка: " + ex.Message);
                }
            }
        }
Beispiel #4
0
        private static void SetRichText(string ccId, string text, bool isFormula)
        {
            string module = $"{Product}.{Class}.{MethodBase.GetCurrentMethod().Name}()";

            Word.Application app = Globals.Chem4WordV3.Application;
            Word.Document    doc = app.ActiveDocument;
            var wordSettings     = new WordSettings(app);

            var cc = GetContentControl(ccId);

            if (isFormula)
            {
                Word.Range         r     = cc.Range;
                List <FormulaPart> parts = FormulaHelper.Parts(text);
                foreach (var part in parts)
                {
                    switch (part.Count)
                    {
                    case 0:     // Separator or multiplier
                    case 1:     // No Subscript
                        if (!string.IsNullOrEmpty(part.Atom))
                        {
                            r.InsertAfter(part.Atom);
                            r.Font.Subscript = 0;
                            r.Start          = cc.Range.End;
                        }
                        break;

                    default:     // With Subscript
                        if (!string.IsNullOrEmpty(part.Atom))
                        {
                            r.InsertAfter(part.Atom);
                            r.Font.Subscript = 0;
                            r.Start          = cc.Range.End;
                        }

                        if (part.Count > 0)
                        {
                            r.InsertAfter($"{part.Count}");
                            r.Font.Subscript = 1;
                            r.Start          = cc.Range.End;
                        }
                        break;
                    }
                }
            }
            else
            {
                cc.Range.Text = text;
            }
        }
Beispiel #5
0
 /// <summary>
 /// 输出开头的一些概况信息
 /// </summary>
 /// <param name="Range"></param>
 /// <remarks>包括标题、施工日期,施工工况等</remarks>
 private void Export_OverView(ref Word.Range Range)
 {
     Word.Range with_1 = Range;
     if (with_1.End > 1) //说明当前range不是在文档的开头,那么就要新起一行
     {
         NewLine(Range, ParagraphStyle.Title_1);
     }
     else //说明当前range就是在文档的开头,那么就直接设置段落样式为“标题”就可以了。
     {
         Range.ParagraphFormat.set_Style(ParagraphStyle.Title_1);
     }
     with_1.InsertAfter(Settings.Default.ProjectName + " 实测数据动态分析:" + dateThisday.ToShortDateString());
     //
     NewLine(Range, ParagraphStyle.Content);
     with_1.InsertAfter("施工日期: " + (dateThisday.ToLongDateString() + '\r' + "施工工况: (***)"));
 }
        /// <summary>
        /// Добавить текст в верхний колонтитул документа: номер страницы и код документа
        /// </summary>
        /// <param name="IBPA"></param>
        public void AddTextInHeader(string IBPA)
        {
            if (Closed)
            {
                throw new Exception("Ошибка при обращении к документу Word. Документ уже закрыт.");
            }

            object replaceStrObj = IBPA;

            try
            {
                // обходим все разделы документа
                for (int i = 2; i <= _document.Sections.Count; i++)
                {
                    //добавляет поле для отображения номера страницы
                    //добавляет поле для отображения  кода документа
                    // выравнивание по центру, размер шрифта 12
                    Word.Range headerRange = _document.Sections[i].Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
                    headerRange.InsertAfter(NewLineChar + "ИБПА." + IBPA + "-01");
                    headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    headerRange.Font.Size = 12;
                }
            }
            catch (Exception error)
            {
                throw new Exception("Ошибка при выполнении замены колонтитула в документе Word.  " + error.Message + " (AddTextInHeader)");
            }
            // завершение функции поиска и замены AddTextInHeader
        }
 private void btnSendFormattedText_Click(object sender, EventArgs e)
 {
     Word.Range range = Globals.ThisAddIn.Application.Selection.Range;
     range.Font.Size = Convert.ToInt32(cboFontSize.SelectedItem);
     range.Font.Name = cboFontNames.SelectedItem.ToString();
     range.InsertAfter(range.Text);
 }
Beispiel #8
0
        //</Snippet6>

        static void VS2008()
        {
            var wordApp = new Word.Application();

            wordApp.Visible = true;
            // docs is a collection of all the Document objects currently
            // open in Word.
            Word.Documents docs = wordApp.Documents;

            // Add a document to the collection and name it doc.
            object useDefaultVal = Type.Missing;

            Word.Document doc = docs.Add(ref useDefaultVal, ref useDefaultVal,
                                         ref useDefaultVal, ref useDefaultVal);

            object n = 0;

            Word.Range range = doc.Range(ref n, ref n);

            range.InsertAfter("Testing, testing, testing. . .");

            //<Snippet14>
            // Call to ConvertToTable in Visual C# 2008 or earlier. This code
            // is not part of the solution.
            var    missing   = Type.Missing;
            object separator = ",";

            range.ConvertToTable(ref separator, 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);
            //</Snippet14>
        }
Beispiel #9
0
        // Word/Excel Utils

        void AddText(Word.Document oDoc, string bookmarkName, string text)
        {
            object oEndOfDoc = bookmarkName;

            Word.Range insertPoint = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            insertPoint.InsertAfter(text);
        }
Beispiel #10
0
        /// <summary> 代码向前缩进 </summary>
        public void Button_AddSpace_Click(object sender, RibbonControlEventArgs e)
        {
            // 要删除或者添加的字符数
            string InsertSpace = "";

            try
            {
                UInt16 SpaceCount = 0;
                SpaceCount = Convert.ToUInt16(this.EditBox_SpaceCount.Text);
                StringBuilder sb = new StringBuilder(4);
                for (var i = 1; i <= SpaceCount; i++)
                {
                    sb.Append(" ");
                }
                InsertSpace = sb.ToString();
            }
            catch (Exception)
            {
                MessageBox.Show("请先设置要添加或者删除的字符数");
                return;
            }
            //
            try
            {
                _app.ScreenUpdating = false;
                int   StartIndex = 0;
                int   EndIndex   = 0;
                Range rg         = _app.Selection.Range;
                StartIndex = rg.Start;
                Range  rgPara = default(Range); //每一段的起始位置
                var    c      = rg.Paragraphs.Count;
                string txt    = "";             // 每一段的文本
                foreach (Paragraph para in rg.Paragraphs)
                {
                    txt = para.Range.Text;
                    if (txt != '\r' + "\a")
                    {
                        // 对于一个表格而言,在每一个表格的末尾,都有一个表示结尾的段落。此段落中有两个字符,所对应的ASCII码分别为13和7。
                        rgPara = para.Range;
                        rgPara.Collapse(Direction: WdCollapseDirection.wdCollapseStart);
                        // 如果Start或End只指定一个的话,那么另一个并不会与指定了的那一个相同的。    rgPara = Doc.Range(para.Range.Start)
                        rgPara.InsertAfter(InsertSpace);
                    }
                    EndIndex = para.Range.End;
                }

                _activeDoc.Range(StartIndex, EndIndex).Select();
            }
            catch (Exception)
            {
                //  MessageBox.Show("代码缩进出错!" & vbCrLf &
                //             ex.Message & vbCrLf & ex.TargetSite.Name, "出错", MessageBoxButtons.OK, MessageBoxIcon.Error)
            }
            finally
            {
                _app.ScreenUpdating = true;
            }
        }
Beispiel #11
0
        private static void SetRichText(Word.ContentControl cc, string text, bool isFormula)
        {
            string module = $"{Product}.{Class}.{MethodBase.GetCurrentMethod().Name}()";

            if (isFormula)
            {
                Word.Range         r     = cc.Range;
                List <FormulaPart> parts = FormulaHelper.Parts(text);
                foreach (var part in parts)
                {
                    switch (part.Count)
                    {
                    case 0:     // Separator or multiplier
                    case 1:     // No Subscript
                        if (!string.IsNullOrEmpty(part.Atom))
                        {
                            r.InsertAfter(part.Atom);
                            r.Font.Subscript = 0;
                            r.Start          = cc.Range.End;
                        }
                        break;

                    default:     // With Subscript
                        if (!string.IsNullOrEmpty(part.Atom))
                        {
                            r.InsertAfter(part.Atom);
                            r.Font.Subscript = 0;
                            r.Start          = cc.Range.End;
                        }

                        if (part.Count > 0)
                        {
                            r.InsertAfter($"{part.Count}");
                            r.Font.Subscript = 1;
                            r.Start          = cc.Range.End;
                        }
                        break;
                    }
                }
            }
            else
            {
                cc.Range.Text = text;
            }
        }
Beispiel #12
0
        /// <summary>
        /// 修改文档
        /// </summary>
        /// <param name="doc">文档内容</param>
        private void ChangeContents(MSWord.Document doc)
        {
            int senTotal = 0, idx = 0, idxTmp = 0;

            MSWord.Range objRange = null;
            string       strTmp   = string.Empty;

            MSWord.Sentences content = null;

            //doc.SetCompatibilityMode((int)MSWord.WdCompatibilityMode.wdWord2010);
            content          = doc.Sentences;
            senTotal         = content.Count;
            pbInsert.Maximum = senTotal;
            for (int i = 1; i <= senTotal; i++)
            {
                Console.WriteLine(i);
                pbInsert.Value = i;
                objRange       = content[i].Words.First;
                idx            = 1;
                while (content[i].Words.Count > idx)
                {//插入字符
                    if (objRange.Text.IndexOf("\r") >= 0)
                    {
                        break;
                    }
                    if (objRange.Text.IndexOf("。") >= 0 || objRange.Text.IndexOf("、") >= 0)
                    {//黑名单
                        objRange = content[i].Words[++idx]; continue;
                    }
                    idxTmp = content[i].Words.Count;
                    objRange.InsertAfter(GetRandomChar());
                    if (content[i].Words.Count > idxTmp)
                    {
                        idx++;
                        //content[i].Words[idx].Font.TextColor.ObjectThemeColor = MSWord.WdThemeColorIndex.wdThemeColorBackground1;
                        content[i].Words[idx].Font.Fill.Transparency = 1F;
                        content[i].Words[idx].Font.Spacing           = -30;
                    }

                    if (idx + 3 < content[i].Words.Count)
                    {
                        idx++;
                    }
                    else
                    {
                        break;
                    }
                    objRange = content[i].Words[idx];
                }
            }

            doc.Content.ParagraphFormat.AddSpaceBetweenFarEastAndAlpha = 0;
            doc.Content.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 0;
        }
Beispiel #13
0
        private void insertText(Word._Document oDoc, string text)
        {
            log("Inserting Text: " + text);

            object oMissing  = System.Reflection.Missing.Value;
            object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

            Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

            //Add text after the chart.
            wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            wrdRng.InsertParagraphAfter();
            wrdRng.InsertAfter(text);
        }
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         if (!String.IsNullOrEmpty(txtSimpleMsg.Text))
         {
             Word.Range range = Globals.ThisAddIn.Application.Selection.Range;
             range.InsertAfter(txtSimpleMsg.Text + "[" + range.Start.ToString() + "|" + range.End.ToString() + "]");
         }
     }
     catch (COMException ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.ToString());
     }
 }
Beispiel #15
0
        private void InsertDetailsAsDefault(List <Utilities.PreferredFileInformation> attachments, Word.Range range, OfficeOutlook.MailItem mailItem, out int numberFailedAttachments)
        {
            numberFailedAttachments = 0;
            for (int n = 0; n < attachments.Count; n++)
            {
                Utilities.PreferredFileInformation fileInfo = attachments[n];

                int endIndex = range.End;

                if (this.insertAsCopy)
                {
                    try
                    {
                        mailItem.Attachments.Add(fileInfo.LocalPath, OfficeOutlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
                    }
                    catch (System.Runtime.InteropServices.COMException ex)
                    {
                        if (ex.Message.ToUpperInvariant() == attachmentWarning.ToUpperInvariant())
                        {
                            numberFailedAttachments++;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                if (this.insertAsLink)
                {
                    range.SetRange(endIndex, endIndex);
                    range.InsertAfter(fileInfo.Url);
                    range.InsertAfter(Environment.NewLine);
                }
            }
        }
Beispiel #16
0
        //Metodo generico para adicionar repetir
        public void AddRepetir(string numContato)
        {
            Word.Range RangeRepetir = Range;

            string repetir = string.Format("repetir 1 até {0} pontuacao \"; |; e |.\"", numContato);

            RangeRepetir.InsertBefore("[");
            RangeRepetir.InsertAfter("{sinal}]");
            RangeRepetir.Select();
            RangeRepetir.Start = RangeRepetir.Start + 1;
            RangeRepetir.Select();
            RangeRepetir.InsertBefore(repetir);
            RangeRepetir.End = RangeRepetir.Start + repetir.Length;
            RangeRepetir.Select();
            RangeRepetir.Application.Selection.Font.Subscript = -1;
        }
Beispiel #17
0
        static void DisplayInWord()
        {
            var wordApp = new Word.Application();

            wordApp.Visible = true;
            // docs is a collection of all the Document objects currently
            // open in Word.
            Word.Documents docs = wordApp.Documents;

            // Add a document to the collection and name it doc.
            Word.Document doc = docs.Add();

            //<Snippet7>
            // Define a range, a contiguous area in the document, by specifying
            // a starting and ending character position. Currently, the document
            // is empty.
            Word.Range range = doc.Range(0, 0);

            // Use the InsertAfter method to insert a string at the end of the
            // current range.
            range.InsertAfter("Testing, testing, testing. . .");
            //</Snippet7>

            // You can comment out any or all of the following statements to
            // see the effect of each one in the Word document.

            // Next, use the ConvertToTable method to put the text into a table.
            // The method has 16 optional parameters. You only have to specify
            // values for those you want to change.

            //<Snippet9>
            // Convert to a simple table. The table will have a single row with
            // three columns.
            range.ConvertToTable(Separator: ",");
            //</Snippet9>

            // Change to a single column with three rows..
            //<Snippet10>
            range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1);
            //</Snippet10>

            // Format the table.
            //<Snippet11>
            range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1,
                                 Format: Word.WdTableFormat.wdTableFormatElegant);
            //</Snippet11>
        }
Beispiel #18
0
        /// <summary>
        /// Inserts the details as HTML.
        /// </summary>
        /// <param name="attachments">The attachments.</param>
        /// <param name="range">The range.</param>
        /// <param name="positionBeforeAdd">The position before add.</param>
        /// <param name="mailItem">The mail item.</param>
        /// <param name="numberFailedAttachments">The number failed attachments.</param>
        /// <returns></returns>
        private int InsertDetailsAsHtml(List <Utilities.PreferredFileInformation> attachments, Word.Range range, int positionBeforeAdd, OfficeOutlook.MailItem mailItem, out int numberFailedAttachments)
        {
            numberFailedAttachments = 0;
            if (this.insertAsCopy)
            {
                for (int n = 0; n < attachments.Count; n++)
                {
                    Utilities.PreferredFileInformation fileInfo = attachments[n];
                    try
                    {
                        mailItem.Attachments.Add(fileInfo.LocalPath, OfficeOutlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
                    }
                    catch (System.Runtime.InteropServices.COMException ex)
                    {
                        if (ex.Message.ToUpperInvariant() == attachmentWarning.ToUpperInvariant())
                        {
                            numberFailedAttachments++;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }

            if (this.insertAsLink)
            {
                // Adding the attachments resets the Range to the top of the document, so we need to move the range
                // to were the user's cursor was when they started the process
                range.SetRange(positionBeforeAdd, positionBeforeAdd);

                for (int n = 0; n < attachments.Count; n++)
                {
                    Utilities.PreferredFileInformation fileInfo = attachments[n];
                    Word.Hyperlink hyperlink = range.Hyperlinks.Add(range, fileInfo.Url, Type.Missing, Type.Missing, fileInfo.ToString());
                    range.SetRange(hyperlink.Range.End, hyperlink.Range.End);
                    range.InsertAfter(Environment.NewLine);
                    range.SetRange(range.End, range.End);
                }

                return(range.End);
            }

            return(0);
        }
Beispiel #19
0
 private void createList()
 {
     MSWord.Range range = wordDoc.GoTo(MSWord.WdGoToItem.wdGoToPage, MSWord.WdGoToDirection.wdGoToAbsolute, QS, 1);
     range.InsertAfter("\r\n");
     range = wordDoc.GoTo(MSWord.WdGoToItem.wdGoToPage, MSWord.WdGoToDirection.wdGoToAbsolute, QS, 1);
     wordDoc.TablesOfContents.Add(range, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, true, ref QS, ref QS);
     wordDoc.TablesOfContents[1].Range.Font.Name = list_font_style;
     wordDoc.TablesOfContents[1].Range.Font.Size = list_font_size;
     wordDoc.TablesOfContents[1].Range.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceExactly;
     wordDoc.TablesOfContents[1].Range.ParagraphFormat.LineSpacing     = 22F;
     range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
     range.Text      = "\n目  录\n\n";
     range.Font.Name = mulu_font_style;
     range.Font.Size = mulu_font_size;
     range.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceExactly;
     range.ParagraphFormat.LineSpacing     = 22F;
 }
Beispiel #20
0
        public Action AddToWordDocument(IResumeDataObject rdo, IResumeFormatObject rfo, Word.Document wordDoc)
        {
            return(() =>
            {
                if (rdo.ExpertiseEntities.Count > 0)
                {
                    // Expertise label
                    Word.Paragraph tagLineLabelPara = wordDoc.Content.Paragraphs.Add();
                    Word.Range r4label = tagLineLabelPara.Range;
                    r4label.Text = "Expertise";
                    r4label.InsertParagraphAfter();
                    r4label.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                    r4label.Font.Name = rfo.HeaderFontName;
                    r4label.Font.Color = rfo.HeaderColorWord;
                    r4label.Font.Size = rfo.HeaderFontSize;

                    // Expertise item-headers
                    List <string> cats = rdo.ExpertiseEntities.Select(T => T.Category).Distinct().ToList();
                    for (int i = 0; i < cats.Count; i++)
                    {
                        Word.Paragraph p = wordDoc.Content.Paragraphs.Add();
                        Word.Range r4 = p.Range;
                        r4.Text = cats[i] + ": ";
                        int titleLength = r4.Text.Length;

                        // Insert expertise(s)
                        List <string> exps = rdo.ExpertiseEntities.Where(T => T.Category == cats[i]).Select(T => T.Expertise).ToList();
                        for (int j = 0; j < exps.Count; j++)
                        {
                            r4.Font.Name = rfo.BodyFontName;
                            r4.Font.Size = rfo.BodyFontSize;
                            r4.InsertAfter(exps[j] + " " + '\u2022' + " ");
                        }
                        r4.Text = r4.Text.Remove(r4.Text.Length - 2);

                        Word.Range titleRange = r4.Duplicate;
                        titleRange.MoveEnd(Word.WdUnits.wdCharacter, titleLength - 1 - titleRange.Characters.Count);
                        titleRange.MoveStart(Word.WdUnits.wdCharacter, 0);
                        titleRange.Font.Name = rfo.CategoryFontName;
                        titleRange.Font.Size = rfo.CategoryFontSize;

                        r4.InsertParagraphAfter();
                    }
                }
            });
        }
        public void AdicionarSpan()
        {
            range.SetRange(Globals.ThisAddIn.Application.Selection.Start, Globals.ThisAddIn.Application.Selection.End);
            string spanContent = range.Text;

            range.Text = textoCampo;

            range.InsertBefore("[");
            range.InsertAfter("]");

            range.SetRange(range.Start + 1, range.End - 1);
            range.Select();
            range.Font.Subscript = 1;
            range.SetRange(range.End, range.End);
            range.Text = spanContent;
            range.Select();
            range.Font.Subscript = 0;
        }
Beispiel #22
0
 private void insertButton_Click(object sender, EventArgs e)
 {
     try
     {
         if (!String.IsNullOrEmpty(insertTextBox.Text))
         {
             Word.Document document = Globals.ThisAddIn.Application.ActiveDocument;
             object        start    = 0;
             object        end      = 0;
             Word.Range    range    = (Word.Range)document.Range(ref start, ref end);
             range.InsertAfter(insertTextBox.Text);
         }
     }
     catch (COMException ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.ToString());
     }
 }
Beispiel #23
0
        //</Snippet22>


        //---------------------------------------------------------------------
        //<Snippet26>
        private void ReplaceParagraphText()
        {
            //<Snippet27>
            Word.Range firstRange  = this.Paragraphs[1].Range;
            Word.Range secondRange = this.Paragraphs[2].Range;

            string firstString  = firstRange.Text;
            string secondString = secondRange.Text;

            //</Snippet27>

            //<Snippet28>
            firstRange.Text  = secondString;
            secondRange.Text = firstString;
            //</Snippet28>

            //<Snippet29>
            firstRange.Select();
            MessageBox.Show(firstRange.Text);
            secondRange.Select();
            MessageBox.Show(secondRange.Text);
            //</Snippet29>

            //<Snippet30>
            object charUnit = Word.WdUnits.wdCharacter;
            object move     = -1; // move left 1

            firstRange.MoveEnd(ref charUnit, ref move);
            //</Snippet30>

            //<Snippet31>
            firstRange.Text = "New content for paragraph 1.";
            //</Snippet31>
            //<Snippet32>
            secondRange.Text = "New content for paragraph 2.";
            //</Snippet32>

            //<Snippet33>
            firstRange.Select();
            MessageBox.Show(firstRange.Text);
            secondRange.Select();
            MessageBox.Show(secondRange.Text);
            //</Snippet33>

            //<Snippet34>
            move = 1;  // move right 1
            firstRange.MoveEnd(ref charUnit, ref move);
            //</Snippet34>

            //<Snippet35>
            secondRange.Delete(ref missing, ref missing);
            //</Snippet35>

            //<Snippet36>
            firstRange.Text = firstString;
            //</Snippet36>

            //<Snippet37>
            firstRange.InsertAfter(secondString);
            firstRange.Select();
            //</Snippet37>
        }
Beispiel #24
0
        public static string TestWord()
        {
            string report = "Chưa kiểm tra Word.";
            //kt word
            object oMissing  = System.Reflection.Missing.Value;
            object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

            Word._Application oWord;
            Word._Document    oDoc;
            oWord         = new Word.Application();
            oWord.Visible = true;
            oDoc          = oWord.Documents.Add(ref oMissing, ref oMissing,
                                                ref oMissing, ref oMissing);

            //Insert a paragraph at the beginning of the document.
            Word.Paragraph oPara1;
            oPara1                   = oDoc.Content.Paragraphs.Add(ref oMissing);
            oPara1.Range.Text        = "hello word ";
            oPara1.Range.Font.Bold   = 1;
            oPara1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.
            oPara1.Range.InsertParagraphAfter();
            //Insert a paragraph at the end of the document.
            Word.Paragraph oPara2;
            object         oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

            oPara2                   = oDoc.Content.Paragraphs.Add(ref oRng);
            oPara2.Range.Text        = "xin chao";
            oPara2.Format.SpaceAfter = 6;
            oPara2.Range.InsertParagraphAfter();
            //Insert another paragraph.
            Word.Paragraph oPara3;
            oRng                     = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            oPara3                   = oDoc.Content.Paragraphs.Add(ref oRng);
            oPara3.Range.Text        = "Bây giờ đây là một bảng:";
            oPara3.Range.Font.Bold   = 0;
            oPara3.Format.SpaceAfter = 24;
            oPara3.Range.InsertParagraphAfter();



            //Insert a 3 x 5 table, fill it with data, and make the first row
            //bold and italic.
            Word.Table oTable;
            Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing);
            oTable.Range.ParagraphFormat.SpaceAfter = 6;
            int    r, c;
            string strText;

            for (r = 1; r <= 3; r++)
            {
                for (c = 1; c <= 5; c++)
                {
                    strText = "r" + r + "c" + c;
                    oTable.Cell(r, c).Range.Text = strText;
                }
            }
            oTable.Rows[1].Range.Font.Bold   = 1;
            oTable.Rows[1].Range.Font.Italic = 1;

            //Add some text after the table.
            Word.Paragraph oPara4;
            oRng   = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            oPara4 = oDoc.Content.Paragraphs.Add(ref oRng);
            oPara4.Range.InsertParagraphBefore();
            oPara4.Range.Text        = "bang khac:";
            oPara4.Format.SpaceAfter = 24;
            oPara4.Range.InsertParagraphAfter();

            //Insert a 5 x 2 table, fill it with data, and change the column widths.
            wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing);
            oTable.Range.ParagraphFormat.SpaceAfter = 6;
            for (r = 1; r <= 5; r++)
            {
                for (c = 1; c <= 2; c++)
                {
                    strText = "r" + r + "c" + c;
                    oTable.Cell(r, c).Range.Text = strText;
                }
            }
            oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2
            oTable.Columns[2].Width = oWord.InchesToPoints(3);

            //Keep inserting text. When you get to 7 inches from top of the
            //document, insert a hard page break.
            object oPos;
            double dPos = oWord.InchesToPoints(7);

            oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter();
            do
            {
                wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                wrdRng.ParagraphFormat.SpaceAfter = 6;
                wrdRng.InsertAfter("A line of text");
                wrdRng.InsertParagraphAfter();
                oPos = wrdRng.get_Information
                           (Word.WdInformation.wdVerticalPositionRelativeToPage);
            }while (dPos >= Convert.ToDouble(oPos));
            object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
            object oPageBreak   = Word.WdBreakType.wdPageBreak;

            wrdRng.Collapse(ref oCollapseEnd);
            wrdRng.InsertBreak(ref oPageBreak);
            wrdRng.Collapse(ref oCollapseEnd);
            wrdRng.InsertAfter("bieu do:");
            wrdRng.InsertParagraphAfter();

            //Insert a chart.
            Word.InlineShape oShape;
            object           oClassType = "MSGraph.Chart.8";

            wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing,
                                                      ref oMissing, ref oMissing, ref oMissing,
                                                      ref oMissing, ref oMissing, ref oMissing);

            //Demonstrate use of late bound oChart and oChartApp objects to
            //manipulate the chart object with MSGraph.
            object oChart;
            object oChartApp;

            oChart    = oShape.OLEFormat.Object;
            oChartApp = oChart.GetType().InvokeMember("Application",
                                                      BindingFlags.GetProperty, null, oChart, null);

            //Change the chart type to Line.
            object[] Parameters = new Object[1];
            Parameters[0] = 4; //xlLine = 4
            oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty,
                                          null, oChart, Parameters);

            //Update the chart image and quit MSGraph.
            oChartApp.GetType().InvokeMember("Update",
                                             BindingFlags.InvokeMethod, null, oChartApp, null);
            oChartApp.GetType().InvokeMember("Quit",
                                             BindingFlags.InvokeMethod, null, oChartApp, null);
            //... If desired, you can proceed from here using the Microsoft Graph
            //Object model on the oChart and oChartApp objects to make additional
            //changes to the chart.

            //Set the width of the chart.
            oShape.Width  = oWord.InchesToPoints(6.25f);
            oShape.Height = oWord.InchesToPoints(3.57f);

            //Add text after the chart.
            wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            wrdRng.InsertParagraphAfter();
            wrdRng.InsertAfter("THE END.");
            oDoc.SaveAs("MyFile.doc", 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);
            oWord.Quit();
            report += "\nĐÃ KIỂM TRA Word";
            return(report);
        }
Beispiel #25
0
        private void InsertTitleBK(MSWord.Document doc, MSWord.Application app)
        {
            int    bknum = 6;
            string bknum_string;

            mydoc.Bookmarks.DefaultSorting = 0;
            mydoc.Bookmarks.ShowHidden     = false;
            MSWord.Section mysec  = mydoc.Sections.Add();
            object         unit   = MSWord.WdUnits.wdLine;
            object         count  = 1;
            object         extend = MSWord.WdMovementType.wdMove;

            MSWord.Range  r    = mysec.Range;
            object        rng  = (object)r;
            SqlConnection conn = new SqlConnection();
            SqlCommand    com  = DatabaseClass.ConnectionToCommad(conn, conStr);

            com.CommandText = "select TitleNum from TitleTable where DocID=@DocID order by TitleNum";
            com.Parameters.Clear();
            com.Parameters.AddWithValue("DocID", IsEditing.DOCID);
            SqlDataReader dr = com.ExecuteReader();

            while (dr.Read())
            {
                //word书签不支持符合“|”,因此在这里需要转换,使用字符“l”
                bknum_string = bknum.ToString();
                if (bknum_string.Length == 1)
                {
                    bknum_string = "00" + bknum_string;
                }
                else if (bknum_string.Length == 2)
                {
                    bknum_string = "0" + bknum_string;
                }
                string   titlenum = dr[0].ToString();
                string[] title    = titlenum.Split('|');
                titlenum = String.Join("l", title);
                string bkmark = "bk" + bknum_string + "_" + titlenum;
                mydoc.Bookmarks.Add(bkmark, ref rng);
                r = GetBKRange(mydoc, bkmark);
                r.Select();
                r.InsertAfter("\n");
                msapp.Selection.MoveDown(ref unit, ref count, ref extend);
                r      = msapp.Selection.Range;
                rng    = (object)r;
                bknum += 1;
            }
            DisposeClose.Disposeclose(dr);
            DisposeClose.Disposeclose(com);
            DisposeClose.Disposeclose(conn);
            //最后插入参考文献

            bknum_string = bknum.ToString();
            if (bknum_string.Length == 1)
            {
                bknum_string = "00" + bknum_string;
            }
            else if (bknum_string.Length == 2)
            {
                bknum_string = "0" + bknum_string;
            }

            string bk_bibliography = "bk" + bknum_string + "_bibliography";

            mydoc.Bookmarks.Add(bk_bibliography, ref rng);
            r = GetBKRange(mydoc, bk_bibliography);
            r.Select();
            r.InsertAfter("\n");
            msapp.Selection.MoveDown(ref unit, ref count, ref extend);
            r            = msapp.Selection.Range;
            rng          = (object)r;
            bknum       += 1;
            bknum_string = bknum.ToString();
            if (bknum_string.Length == 1)
            {
                bknum_string = "00" + bknum_string;
            }
            else if (bknum_string.Length == 2)
            {
                bknum_string = "0" + bknum_string;
            }
            string bk_bcontent = "bk" + bknum_string + "_bcontent";

            mydoc.Bookmarks.Add(bk_bcontent, ref rng);
        }
Beispiel #26
0
        private void InsertOffsiteSig(Outlook.MailItem oMsg)
        {
            object oBookmarkName       = "_MailAutoSig";    // Outlook internal bookmark for location of the e-mail signature
            string oOffsiteBookmark    = "OffsiteBookmark"; // bookmark to be created in Outlook for the Offsite tagline
            object oOffsiteBookmarkObj = oOffsiteBookmark;

            Word.Document SigDoc = oMsg.GetInspector.WordEditor as Word.Document; // edit the message using Word

            string bf = oMsg.BodyFormat.ToString();                               // determine the message body format (text, html, rtf)

            //  Go to the e-mail signature bookmark, then set the cursor to the very end of the range.
            //  This is where we will insert/remove our tagline, and the start of the new range of text

            Word.Range r           = SigDoc.Bookmarks.get_Item(ref oBookmarkName).Range;
            object     collapseEnd = Word.WdCollapseDirection.wdCollapseEnd;

            r.Collapse(ref collapseEnd);

            string[] taglines = GetRssItem();  // Get tagline information from the RSS XML file and place into an array

            // Loop through the array and insert each line of text separated by a newline

            foreach (string taglineText in taglines)
            {
                r.InsertAfter(taglineText + "\n");
            }
            r.InsertAfter("\n");

            // Add formatting to HTML/RTF messages

            if (bf != "olFormatPlain" && bf != "olFormatUnspecified")
            {
                SigDoc.Hyperlinks.Add(r, taglines[2]);         // turn the link text into a hyperlink
                r.Font.Underline = 0;                          // remove the hyperlink underline
                r.Font.Color     = Word.WdColor.wdColorGray45; // change all text to Gray45
                r.Font.Size      = 8;                          // Change the font size to 8 point
                r.Font.Name      = "Arial";                    // Change the font to Arial
            }

            r.NoProofing = -1;  // turn off spelling/grammar check for this range of text

            object range1 = r;

            SigDoc.Bookmarks.Add(oOffsiteBookmark, ref range1);  // define this range as our custom bookmark

            if (bf != "olFormatPlain" && bf != "olFormatUnspecified")
            {
                // Make the first line BOLD only for HTML/RTF messages

                Word.Find f = r.Find;
                f.Text           = taglines[0];
                f.MatchWholeWord = true;
                f.Execute();
                while (f.Found)
                {
                    r.Font.Bold = -1;
                    f.Execute();
                }
            }
            else
            {
                // otherwise turn the plain text hyperlink into an active hyperlink
                // this is done here instead of above due to the extra formatting needed for HTML/RTF text

                Word.Find f = r.Find;
                f.Text           = taglines[2];
                f.MatchWholeWord = true;
                f.Execute();
                SigDoc.Hyperlinks.Add(r, taglines[2]);
            }
            r.NoProofing = -1;  // disable spelling/grammar checking on the updated range
            r.Collapse(collapseEnd);
        }
Beispiel #27
0
        private void CreateDocument()
        {
            if (cboAssRef.SelectedItem == null)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Please select an Assyst Reference.", "Assyst Case", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string strAssRef = "";

            if (this.Text == "DTaS APPendix - Add Assyst Case")
            {
                strAssRef = this.txtAssRef.Text; //Textbox Assyst Ref
            }
            else
            {
                strAssRef = this.cboAssRef.SelectedValue.ToString(); //Combobox Ass Ref
            }

            object oMissing  = System.Reflection.Missing.Value;
            object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

            try
            {
//Start Word and create a new document.
                Word._Application oWord;
                Word._Document    oDoc;
                oWord         = new Word.Application();
                oWord.Visible = true;
                oDoc          = oWord.Documents.Add(ref oMissing, ref oMissing,
                                                    ref oMissing, ref oMissing);

                //Insert a paragraph at the beginning of the document.
                Word.Paragraph oPara1;
                oPara1                   = oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara1.Range.Text        = "Assyst Reference: " + strAssRef;
                oPara1.Range.Font.Bold   = 1;
                oPara1.Format.SpaceAfter = 6; //6 pt spacing after paragraph.
                oPara1.Range.InsertParagraphAfter();

                Word.Range wrdRng = oDoc.Range(0);
                wrdRng.Font.Bold = 0;
                wrdRng.ParagraphFormat.SpaceAfter = 6;
                if (cboBDAppNo.SelectedItem == null)
                {
                    wrdRng.InsertAfter("BDApp Number: ");
                }
                else
                {
                    wrdRng.InsertAfter("BDApp Number: " + cboBDAppNo.Text);
                }
                wrdRng.InsertParagraphAfter();
                wrdRng.InsertAfter("BDApp Name: " + txtBDAppName.Text);
                wrdRng.InsertParagraphAfter();
                wrdRng.InsertAfter("Date Opened: " + txtDateOpened.Text);
                wrdRng.InsertParagraphAfter();
                wrdRng.InsertAfter("SLA Target: " + txtSLATarget.Text);
                wrdRng.InsertParagraphAfter();
                wrdRng.InsertAfter("Summary: " + txtSummary.Text);
                wrdRng.InsertParagraphAfter();
                if (cboAssignDev.SelectedItem == null)
                {
                    wrdRng.InsertAfter("Assigned to Developer: ");
                }
                else
                {
                    wrdRng.InsertAfter("Assigned to Developer: " + cboAssignDev.Text);
                }
                wrdRng.InsertParagraphAfter();
                wrdRng.InsertAfter("Acknowledgement Email Sent: " + txtEmailSent.Text);
                wrdRng.InsertParagraphAfter();
                wrdRng.InsertAfter("Email Chased: " + txtEmailChased.Text);
                wrdRng.InsertParagraphAfter();
                wrdRng.InsertAfter("Notes: " + txtNotes.Text);
                wrdRng.InsertParagraphAfter();
                wrdRng.InsertAfter("Next Action Date: " + txtNAD.Text);
                wrdRng.InsertParagraphAfter();
                wrdRng.InsertAfter("Next Action: " + txtNA.Text);
                wrdRng.InsertParagraphAfter();
                wrdRng.InsertAfter("Date Resolved: " + txtDateResolved.Text);
                wrdRng.InsertParagraphAfter();
                if (cboFix.SelectedItem == null)
                {
                    wrdRng.InsertAfter("Fix Applied: ");
                }
                else
                {
                    wrdRng.InsertAfter("Fix Applied: " + cboFix.Text);
                }
                wrdRng.InsertParagraphAfter();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #28
0
        //создание нового документа ворд
        private void NewDocWord()
        {
            try
            {
                //создание документа
                application = new Word.Application();
                object missing = Type.Missing;
                application.Documents.Add();

                Word.Paragraph para = application.Documents[1].Paragraphs.Add();

                for (int i = 0; i < 5; i++)
                {
                    application.Documents[1].Paragraphs.Add();
                }

                Word.Range range = application.Documents[1].Paragraphs[1].Range;
                Word.Table table = application.Documents[1].Paragraphs[1].Range.Tables.Add(range, 1, 2);
                //application.Documents[1].Tables.Add(range, 1, 2);
                table.Borders.Enable = 1;

                Word.Range range2 = application.Documents[1].Paragraphs[2].Range;
                range2.InsertAfter("123");



                //range.Font.Name = @"Times New Roman";
                //table.Rows[1].Cells[2].Range.Text = @"Державний вищий навальний заклад «Криворізький національний університет» State Institution of Higner Education" + Environment.NewLine + "«Kryvyi Rig National University»";

                ////выравнивание по центру
                //table.Rows[1].Cells[2].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                ////отступ после
                //table.Rows[1].Cells[2].Range.ParagraphFormat.SpaceAfter = 0;
                ////отступ до
                //table.Rows[1].Cells[2].Range.ParagraphFormat.SpaceBefore = 0;
                ////одинарный интервал
                //table.Rows[1].Cells[2].Range.ParagraphFormat.Space1();

                //table.Rows[1].Cells[2].Range.Font.Size = 12;
                ////RGB цвет
                //Color c = Color.FromArgb(23, 74, 177);
                //var myWdColor = (Microsoft.Office.Interop.Word.WdColor)(c.R + 0x100 * c.G + 0x10000 * c.B);
                //table.Rows[1].Cells[2].Range.Font.Color = myWdColor;

                //object missing = Type.Missing;
                //Word.Paragraph para = document.Paragraphs.Add(ref missing);

                //for (int i = 0; i < 5; i++)
                //{
                //    document.Paragraphs.Add(ref missing);
                //}

                //document.Paragraphs[1].Range.Text = "Академічна довідка";



                //foreach(Word.Row row in table.Rows)
                //{
                //    foreach(Word.Cell cell in row.Cells)
                //    {
                //        if (cell.RowIndex == 1)
                //        {
                //            cell.Range.Text = "Колонка " + cell.ColumnIndex.ToString();
                //            cell.Range.Bold = 1;
                //            cell.Range.Font.Name = "verdana";
                //            cell.Range.Font.Size = 10;

                //            cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                //        }
                //    }
                //}
            }
            catch
            {
                MessageBox.Show("Error!");
            }
            finally
            {
                application.ActiveDocument.Save();
                application.ActiveDocument.Close();
                application.Quit();
            }
        }
Beispiel #29
0
        private void button1_Click(object sender, EventArgs e)
        {
            //新建文档
            // Word.Application newapp = new Word.Application();//用这句也能初始化
            Word.Application newapp = new Word.ApplicationClass();
            Word.Document    newdoc;
            object           nothing = System.Reflection.Missing.Value;                                //用于作为函数的默认参数

            newdoc         = newapp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing); //生成一个word文档
            newapp.Visible = true;                                                                     //是否显示word程序界面

            //页面设置
            //newdoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape ;
            //newdoc.PageSetup.PageWidth = newapp.CentimetersToPoints(21.0f);
            //newdoc.PageSetup.PageHeight = newapp.CentimetersToPoints(29.7f);
            newdoc.PageSetup.PaperSize      = Word.WdPaperSize.wdPaperA4;
            newdoc.PageSetup.Orientation    = Word.WdOrientation.wdOrientPortrait;
            newdoc.PageSetup.TopMargin      = 57.0f;
            newdoc.PageSetup.BottomMargin   = 57.0f;
            newdoc.PageSetup.LeftMargin     = 57.0f;
            newdoc.PageSetup.RightMargin    = 57.0f;
            newdoc.PageSetup.HeaderDistance = 30.0f;//页眉位置

            //设置页眉
            newapp.ActiveWindow.View.Type              = Word.WdViewType.wdOutlineView;       //视图样式。
            newapp.ActiveWindow.View.SeekView          = Word.WdSeekView.wdSeekPrimaryHeader; //进入页眉设置,其中页眉边距在页面设置中已完成
            newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            //插入页眉图片
            string headerfile = "d:\\header.jpg";

            // this.outpicture(headerfile, Properties.Resources.header);
            Word.InlineShape shape1 = newapp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref nothing, ref nothing, ref nothing);
            shape1.Height = 30;
            shape1.Width  = 80;
            newapp.ActiveWindow.ActivePane.Selection.InsertAfter("中建东北院");
            //去掉页眉的那条横线
            newapp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleNone;
            newapp.ActiveWindow.ActivePane.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = false;
            newapp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;//退出页眉设置

            //添加页码
            Word.PageNumbers pns = newapp.Selection.Sections[1].Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;
            pns.NumberStyle               = Word.WdPageNumberStyle.wdPageNumberStyleNumberInDash;
            pns.HeadingLevelForChapter    = 0;
            pns.IncludeChapterNumber      = false;
            pns.ChapterPageSeparator      = Word.WdSeparatorType.wdSeparatorHyphen;
            pns.RestartNumberingAtSection = false;
            pns.StartingNumber            = 0;
            object pagenmbetal = Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
            object first       = true;

            newapp.Selection.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first);

            //文字设置(Selection表示当前选择集,如果当前没有选择对像,则指对光标所在处进行设置)
            newapp.Selection.Font.Size  = 14;
            newapp.Selection.Font.Bold  = 0;
            newapp.Selection.Font.Color = Word.WdColor.wdColorBlack;
            newapp.Selection.Font.Name  = "宋体";

            //段落设置
            newapp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly;
            newapp.Selection.ParagraphFormat.LineSpacing     = 20;
            newapp.Selection.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            newapp.Selection.ParagraphFormat.FirstLineIndent = 30;
            //  newdoc.Content.InsertAfter(WindowsFormsApplication1.Properties.Resources.PreViewWords);



            //插入公式
            object oEndOfDoc = "\\endofdoc";

            Word.Range rang1             = newdoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            object     fieldType         = Word.WdFieldType.wdFieldEmpty;
            object     formula           = @"eq \i(a,b,ξxdx)";
            object     presrveFormatting = false;

            rang1.Text           = formula.ToString();
            rang1.Font.Size      = 14;
            rang1.Font.Bold      = 0;
            rang1.Font.Subscript = 0;
            rang1.Font.Color     = Word.WdColor.wdColorBlue;
            rang1.Font.Name      = "宋体";
            rang1.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
            rang1.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphRight;
            newdoc.Fields.Add(rang1, ref fieldType, ref formula, ref presrveFormatting);

            //将文档的前三个字替换成"asdfasdf",并将其颜色设为蓝色
            object start = 0;
            object end   = 3;

            Word.Range rang2 = newdoc.Range(ref start, ref end);
            rang2.Font.Color = Word.WdColor.wdColorBlue;
            rang2.Text       = "as签";

            //将文档开头的"as"替换成"袁波"
            rang1.Start = 0;
            rang1.End   = 2;
            rang1.Text  = "这是一个";
            rang1.InsertAfter("书");
            //rang1.Select();
            object codirection = Word.WdCollapseDirection.wdCollapseStart;

            rang1.Collapse(ref codirection);//将rang1的起点和终点都定于起点或终点

            //对前三个字符进行加粗
            newdoc.Range(ref start, ref end).Bold = 1;
            object rang = rang2;

            newdoc.Bookmarks.Add("yb", ref rang);


            object unite = Word.WdUnits.wdStory;

            newapp.Selection.EndKey(ref unite, ref nothing);//将光标移至文末
            newapp.Selection.Font.Size = 10;
            newapp.Selection.TypeText("...............................(式1)\n");


            //插入图片
            newapp.Selection.EndKey(ref unite, ref nothing);//将光标移至文末
            //newapp.Selection.HomeKey(ref unite, ref nothing);//将光标移至文开头
            newapp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
            newapp.Selection.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            object LinkToFile       = false;
            object SaveWithDocument = true;
            object Anchor           = newapp.Selection.Range;
            string picname          = "d:\\kk.jpg";

            //     this.outpicture(picname, Properties.Resources.IMG_2169);
            newdoc.InlineShapes.AddPicture(picname, ref LinkToFile, ref SaveWithDocument, ref Anchor);
            newdoc.InlineShapes[1].Height = 200;
            newdoc.InlineShapes[1].Width  = 200;
            newdoc.Content.InsertAfter("\n");
            newapp.Selection.EndKey(ref unite, ref nothing);//将光标移至文末
            newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newapp.Selection.Font.Size = 10;
            newapp.Selection.TypeText("图1 袁冶\n");
            newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            newdoc.Content.InsertAfter("\n");
            newdoc.Content.InsertAfter("\n");

            //用这种方式也可以插入公式,并且这种方法更简单
            newapp.Selection.Font.Size = 14;
            newapp.Selection.InsertFormula(ref formula, ref nothing);
            newapp.Selection.Font.Size = 10;
            newapp.Selection.TypeText("..............................(式2)\n");
            newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newapp.Selection.TypeText("表1 电子产品\n");

            //插入表格
            Word.Table table1 = newdoc.Tables.Add(newapp.Selection.Range, 4, 3, ref nothing, ref nothing);
            newdoc.Tables[1].Cell(1, 1).Range.Text = "产品\n项目";
            newdoc.Tables[1].Cell(1, 2).Range.Text = "电脑";
            newdoc.Tables[1].Cell(1, 3).Range.Text = "手机";
            newdoc.Tables[1].Cell(2, 1).Range.Text = "重量(kg)";
            newdoc.Tables[1].Cell(3, 1).Range.Text = "价格(元)";
            newdoc.Tables[1].Cell(4, 1).Range.Text = "共同信息";
            newdoc.Tables[1].Cell(4, 2).Range.Text = "信息A";
            newdoc.Tables[1].Cell(4, 3).Range.Text = "信息B";


            table1.Select();
            table1.Rows.Alignment = Word.WdRowAlignment.wdAlignRowCenter;//整个表格居中
            newapp.Selection.Cells.VerticalAlignment   = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newapp.Selection.Cells.HeightRule          = Word.WdRowHeightRule.wdRowHeightExactly;
            newapp.Selection.Cells.Height                          = 40;
            table1.Rows[2].Height                                  = 20;
            table1.Rows[3].Height                                  = 20;
            table1.Rows[4].Height                                  = 20;
            table1.Range.ParagraphFormat.Alignment                 = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newapp.Selection.Cells.Width                           = 150;
            table1.Columns[1].Width                                = 75;
            table1.Cell(1, 1).Range.ParagraphFormat.Alignment      = Word.WdParagraphAlignment.wdAlignParagraphRight;
            table1.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;



            //表头斜线
            table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Visible   = true;
            table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Color     = Word.WdColor.wdColorGreen;
            table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineWidth = Word.WdLineWidth.wdLineWidth050pt;

            //表格边框
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Color     = Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].LineWidth = Word.WdLineWidth.wdLineWidth050pt;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Color     = Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].LineWidth = Word.WdLineWidth.wdLineWidth050pt;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Color     = Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineStyle = Word.WdLineStyle.wdLineStyleDoubleWavy;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Color     = Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineStyle = Word.WdLineStyle.wdLineStyleDoubleWavy;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Color     = Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleDouble;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Color     = Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineStyle = Word.WdLineStyle.wdLineStyleDouble;

            //合并单元格
            newdoc.Tables[1].Cell(4, 2).Merge(table1.Cell(4, 3));

            //删除图片
            this.delpictfile(headerfile);
            this.delpictfile(picname);


            //保存文档
            object name = "c:\\yb3.doc";

            newdoc.SaveAs(ref name, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
                          ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
                          ref nothing, ref nothing);

            //关闭文档
            object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;

            newdoc.Close(ref nothing, ref nothing, ref nothing);
            newapp.Application.Quit(ref saveOption, ref nothing, ref nothing);
            newdoc = null;
            newapp = null;
            ShellExecute(IntPtr.Zero, "open", "c:\\yb3.doc", "", "", 3);
        }
Beispiel #30
0
 public void AddSpan(string condicao)
 {
     //add o span na selecao
     Range.InsertBefore("[");
     Range.InsertAfter("]");
     Range.Select();
     Range.Application.Selection.Font.Color = Word.WdColor.wdColorRed;
     Range.Start = Range.Start + 1;
     Range.Select();
     Range.InsertBefore(condicao);
     Range.End = Range.Start + condicao.Length;
     Range.Select();
     Range.Application.Selection.Font.Subscript = -1;
 }