This project has moved and is read-only. For the latest updates, please go here.

How to replace text with table in a word document?

Apr 7, 2016 at 8:57 PM
Hi,

Can I replace text with Table in DocX?

I need to do the same thing in this article in spireDOC

http://www.e-iceblue.com/Tutorials/Spire.Doc/Spire.Doc-Program-Guide/Table/How-to-replace-text-with-table-in-a-word-document-in-C.html
May 10, 2016 at 3:48 PM
Edited May 10, 2016 at 3:50 PM
Hello. This is what I use to replace texts with a table in my code (with commandString being the text to replace):
        /// <summary>
        /// Replace the text with NovaCode.Table
        /// </summary>
        /// <param name="doc">DocX document</param>
        /// <param name="commandString">string command to replace</param>
        /// <param name="table">Table object to replace with</param>
        /// <param name="paragraphs">Paragraphs list</param>
        private void ReplaceTextWithTable(DocX doc, string commandString, Table table, ReadOnlyCollection<Paragraph> paragraphs = null)
        {
            try
            {
                ReadOnlyCollection<Paragraph> docParagraphs;
                if (paragraphs == null)
                    docParagraphs = doc.Paragraphs;
                else
                    docParagraphs = paragraphs;

                foreach (var paragraph in docParagraphs)
                {
                    var valuesIndex = paragraph.FindAll(commandString, RegexOptions.IgnoreCase);
                    if (valuesIndex.Count > 0)
                    {
                        foreach (var valueIndex in valuesIndex)
                        {
                            paragraph.InsertTableBeforeSelf(table);
                            paragraph.RemoveText(valueIndex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }