Search through document and find strings

Apr 6, 2016 at 7:25 AM
Edited Apr 6, 2016 at 7:41 AM
I'm using DocX library to replace text inside word document. I want to somehow find all strings between "[]" inside my template docx file, for example [Name], [LastName], [Date] etc... and replace it with values which I previously load to datagridview which have same column name(Name, LastName, Date). I'm not sure what should I put inside for input to search hole word document and replace it with Here is what I have so far:
            foreach (DataGridViewRow dataGridViewRow in list)
            {
                try
                    {
                        string template = txtUcitajTemplate.Text;
                        string text2 = "Aneksi";
                        if (!System.IO.Directory.Exists(text2))
                        {
                            System.IO.Directory.CreateDirectory(text2);
                        }
                        string path = string.Format("{0}.docx", dataGridViewRow.Cells["Name"].Value.ToString());
                        string path2 = System.IO.Path.Combine(text2, path);

                        using (DocX document = DocX.Load(template))
                        {
                            string patternstart = Regex.Escape("[");
                            string patternend = Regex.Escape("]");
                            string regexexpr = patternstart + @"(.*?)" + patternend;
                            // document.ReplaceText(regexexpr, dataGridViewRow.Cells[0].Value.ToString());
            // document.ReplaceText(regexexpr, dataGridViewRow.Cells[1].Value.ToString());
                            var regex = new regex("[.*?]");
                            var matches = regex.matches(input); //your matches: name, name@gmail.com
                            foreach (var match in matches) // e.g. you can loop through your matches like this
                            {
                               document.ReplaceText(match.ToString(), dataGridViewRow.Cells["Name"].Value.ToString());
                               document.ReplaceText(match.ToString(), dataGridViewRow.Cells["LastName"].Value.ToString());
                            }
                        document.SaveAs(path2);                     
                    }
                   
                }
              
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
Any suggestions?
Developer
Apr 6, 2016 at 11:34 AM
Maybe try using bookmarks? You can find exaple code in sources.
        private static void Bookmarks()
        {
            Console.WriteLine("\tBookmarks()");

            using (var document = DocX.Create(@"docs\Bookmarks.docx"))
            {
                var paragraph = document.InsertBookmark("firstBookmark");

                var paragraph2 = document.InsertParagraph("This is a paragraph which contains a ");
                paragraph2.AppendBookmark("secondBookmark");
                paragraph2.Append("bookmark");

                paragraph2.InsertAtBookmark("handy ", "secondBookmark");

                document.Save();
                Console.WriteLine("\tCreated: docs\\Bookmarks.docx\n");
            
            }
        }
        /// <summary>
        /// Loads a document 'DocumentWithBookmarks.docx' and changes text inside bookmark keeping formatting the same.
        /// This code creates the file 'BookmarksReplaceTextOfBookmarkKeepingFormat.docx'.
        /// </summary>
        private static void BookmarksReplaceTextOfBookmarkKeepingFormat()
        {
            Console.WriteLine("\tBookmarksReplaceTextOfBookmarkKeepingFormat()");

            using (DocX docX = DocX.Load("DocumentWithBookmarks.docx"))
            {
                foreach (Bookmark bookmark in docX.Bookmarks)
                    Console.WriteLine("\t\tFound bookmark {0}", bookmark.Name);

                // Replace bookmars content
                docX.Bookmarks["bmkNoContent"].SetText("Here there was a bookmark");
                docX.Bookmarks["bmkContent"].SetText("Here there was a bookmark with a previous content");
                docX.Bookmarks["bmkFormattedContent"].SetText("Here there was a formatted bookmark");

                docX.SaveAs(@"docs\BookmarksReplaceTextOfBookmarkKeepingFormat.docx");
            }
            Console.WriteLine("\tCreated: docs\\BookmarksReplaceTextOfBookmarkKeepingFormat.docx");
        }
Apr 6, 2016 at 1:49 PM
Tnx, I think I understand what did you do, but I'm doing something wrong. I've created word doc with named bookmarks manually and loading its path to textbox. Maybe that's wrong, because I'm not getting document.Bookmarks, only InsertBoomarks, ValidateBookmarks, etcc... Could you please help me?
                      string template = txtUcitajTemplate.Text;

                        using (Novacode.DocX document = DocX.Load(template))
                        {


                            foreach (Novacode.Bookmark bookmark in document.Bookmarks)
                            {
                                document.Bookmarks["NameBookmark"].SetText(dataGridViewRow.Cells["Name"].Value.ToString());
                                document.Bookmarks["LastNameBookmark"].SetText(dataGridViewRow.Cells["LastName"].Value.ToString());

                            }
                       }

                        document.SaveAs(path2);

                        
                    }
Developer
Apr 6, 2016 at 1:57 PM
I suggest to download the whole source code. There should be a Bookmarks.docx attached. Play with it and see what it returns, how it looks etc.
Apr 8, 2016 at 8:25 AM
Sorry, I was using older version of DocX, updated to 1.0.22 and its fine now. Bellow code is if I manually specify bookmark name and datagridview column names. How can I automatically find (parse) all bookmarks (by name) and replace them with text (values) from datagridview?
           foreach (DataGridViewRow dataGridViewRow in list)
            {
                try
                    {

                        using (Novacode.DocX document = DocX.Load(template))
                        {

                            foreach (Novacode.Bookmark bookmark in document.Bookmarks)
                            {

                                document.Bookmarks["Name"].SetText(dataGridViewRow.Cells["Name"].Value.ToString());
                                document.Bookmarks["LastName"].SetText(dataGridViewRow.Cells["LastName"].Value.ToString());
                                           
                            }
                        document.SaveAs(path2);           

                    } 
                }

                
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
Developer
Apr 8, 2016 at 8:35 AM
Please download the source code. Open Examples, go to BookmarksReplaceTextOfBookmarkKeepingFormat. You will notice
    Console.WriteLine("\t\tFound bookmark {0}", bookmark.Name);
This means bookmark.Name gives you the name you're looking for. So you need to create variable like var myvalue = docX.Bookmarks; and go from there.
    private static void BookmarksReplaceTextOfBookmarkKeepingFormat()
    {
        Console.WriteLine("\tBookmarksReplaceTextOfBookmarkKeepingFormat()");

        using (DocX docX = DocX.Load("DocumentWithBookmarks.docx"))
        {
            foreach (Bookmark bookmark in docX.Bookmarks)
                Console.WriteLine("\t\tFound bookmark {0}", bookmark.Name);

            // Replace bookmars content
            docX.Bookmarks["bmkNoContent"].SetText("Here there was a bookmark");
            docX.Bookmarks["bmkContent"].SetText("Here there was a bookmark with a previous content");
            docX.Bookmarks["bmkFormattedContent"].SetText("Here there was a formatted bookmark");

            docX.SaveAs(@"docs\BookmarksReplaceTextOfBookmarkKeepingFormat.docx");
        }
        Console.WriteLine("\tCreated: docs\\BookmarksReplaceTextOfBookmarkKeepingFormat.docx");
    }
Apr 22, 2016 at 11:04 AM
Edited Apr 22, 2016 at 11:09 AM
Still no solution for this, sorry. I'm trying something like this, but no luck and lack of knowledge :) Please?
           foreach (DataGridViewRow dataGridViewRow in list)
            {
                try
                    {

                        using (Novacode.DocX document = DocX.Load(template))
                        {

             for (int i = 1; i <= document.Bookmarks.Count; i++)
               {
                   for (int j = 0; j <= dataGridViewRow.Cells.Count; j++)
                     {

                     document.Bookmarks[i].Name = dataGridViewRow.Cells[j].Value.ToString();

                     }
               }
                 document.SaveAs(path2);           

                 } 
                    catch (System.Exception ex)
                        {
                           MessageBox.Show(ex.Message);
                          }
                }
           }
Apr 22, 2016 at 2:01 PM
It's working now, but, when it comes to the last bookmark, it binds last two cell values.
           foreach (DataGridViewRow dataGridViewRow in list)
            {
                try
                    {

                        using (Novacode.DocX document = DocX.Load(template))
                        {


                            int i = 0;

                            foreach (Novacode.Bookmark bookmark in document.Bookmarks)
                            {


                                  document.Bookmarks[bookmark.Name].SetText(dataGridViewRow.Cells[i + 1].Value.ToString());

                                i++;

                            }
                 document.SaveAs(path2);           

                 } 
                    catch (System.Exception ex)
                        {
                           MessageBox.Show(ex.Message);
                          }
                }
           }