insert repeating data in table of word document using open xml 2.0

gogi100 51 Reputation points
2021-06-21T08:31:01.657+00:00

i have sharepoint list where user populate some fields. i made event receiver that when user update some fields in document library is created document where inserting repeating data in table. i have problem. my code is

public bool CreateDocument(string sFilename, string sContentType, string sList, string id, string broj, string datum, string opis, string ponudjac, string ponudjacadresa, string ponudjacemail, string sektor, string sektormestorada, string subjektrevizije,  string usluge, string akontacija, string udaljenostodsubjekta, string rukovodilac, string url)
           {
               try
               {
                   SPSite site = new SPSite(url);
                   using (SPWeb web = site.OpenWeb())
                   {


                       SPList list = web.Lists[sList];
                       // this always uses root folder
                       SPFolder folder = list.RootFolder;
                       SPFileCollection fcol = folder.Files;

                       // find the template url and open
                       string sTemplate = list.ContentTypes[sContentType].DocumentTemplateUrl;
                       SPFile spf = web.GetFile(sTemplate);
                       byte[] binFile = spf.OpenBinary();
                       // Url for file to be created
                       string destFile = fcol.Folder.Url + "/" + sFilename;


                       SPFile addedFile = fcol.Add(destFile, binFile);
                       SPItem newItem = addedFile.Item;
                       newItem.Update();
                       addedFile.Update();

                        SPQuery query = new SPQuery();
                        query.Query = "<Where><Eq>" + "<FieldRef Name='FileLeafRef' />" + "<Value Type='Text'>" + sFilename + "</Value>" + "</Eq>" + "</Where>";

                       SPListItemCollection collection = list.GetItems(query);
                        SPFile file = collection[0].File;
                        byte[] byteArray = file.OpenBinary();
                        using (MemoryStream memStr = new MemoryStream())
                        {
                            memStr.Write(byteArray, 0, byteArray.Length);

                            using (WordprocessingDocument doc = WordprocessingDocument.Open(memStr, true))
                            {
                                //create XML string matching custom XML part


                                MainDocumentPart main = doc.MainDocumentPart;
                                Table TabelaZapisnik = main.Document.Body.Descendants<Table>().First();
                                // Get the last row in the table.
                                TableRow Red = TabelaZapisnik.Elements<TableRow>().Last();
                                TableRow rowCopy = (TableRow)Red.CloneNode(true);
                                rowCopy.Descendants<TableCell>().ElementAt(0).Append(new Paragraph(new Run(new Text("1"))));
                                rowCopy.Descendants<TableCell>().ElementAt(1).Append(new Paragraph(new Run(new Text("Test1"))));
                                rowCopy.Descendants<TableCell>().ElementAt(2).Append(new Paragraph(new Run(new Text("Test2"))));
                                rowCopy.Descendants<TableCell>().ElementAt(3).Append(new Paragraph(new Run(new Text("Test3"))));
                                rowCopy.Descendants<TableCell>().ElementAt(4).Append(new Paragraph(new Run(new Text("Test4"))));
                                rowCopy.Descendants<TableCell>().ElementAt(5).Append(new Paragraph(new Run(new Text("Test5"))));
                                TabelaZapisnik.AppendChild(rowCopy);
                                // Remove the empty placeholder row from the table.
                                TabelaZapisnik.RemoveChild(Red);
                                // Save the changes to the table back into the document.
                                main.Document.Save();


                                //closing WordprocessingDocument automatically saves the document
                            }
                        }
                            //OpenXml kreiranje dokumenata - kraj



                      return true;
                   }
               }
               catch (SPException spEx)
               {
                   // file already exists?
                   if (spEx.ErrorCode == -2130575257)
                       return false;
                   else
                       throw spEx;
               }

the created document from template in document library is created but he is not updated with values: Test1,Test2,Test3,Test4 and Test5.

Microsoft 365 and Office SharePoint Server Development
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. gogi100 51 Reputation points
    2021-06-21T09:18:04.267+00:00

    ![107528-untitled.jpg]1

    my template document is like on picture above, but table is empty.

    0 comments No comments

  2. MichaelHan-MSFT 18,126 Reputation points
    2021-06-22T09:14:41.943+00:00

    Hi @gogi100 ,

    For this issue, you could add breakpoint when getting this file in the below position. If you could get the file, something may be wrong with the code when using openxml. And I'm not a expert with openxml, you'd better ask in SO: https://stackoverflow.com/questions/tagged/openxml

    SPListItemCollection collection = list.GetItems(query);  
    SPFile file = collection[0].File;  
    

    If an Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  3. gogi100 51 Reputation points
    2021-06-23T09:34:49.89+00:00

    i changed code and it works. the Document is created in document library and the document is populated with fields in list, but i want update fields ID Субјект and ID ПонудеСмештај in document library but this code it's not works

                               using (MemoryStream memStr = new MemoryStream())
                                 {
                                     memStr.Write(byteArray, 0, byteArray.Length);
    
                                     using (WordprocessingDocument doc = 
                              WordprocessingDocument.Open(memStr, true))
                                     {
                                         //create XML string matching custom XML part
    
    
                                         MainDocumentPart main = doc.MainDocumentPart;
                                         Table TabelaZapisnik = 
                                 main.Document.Body.Descendants<Table>().First();
                                         // Get the last row in the table.
                                         TableRow Red = TabelaZapisnik.Elements<TableRow>().Last();
                                         TableRow rowCopy = (TableRow)Red.CloneNode(true);
                                         rowCopy.Descendants<TableCell>().ElementAt(0).Append(new Paragraph(new Run(new Text("1"))));
                                         rowCopy.Descendants<TableCell>().ElementAt(1).Append(new Paragraph(new Run(new Text("Test1"))));
                                         rowCopy.Descendants<TableCell>().ElementAt(2).Append(new Paragraph(new Run(new Text("Test2"))));
                                         rowCopy.Descendants<TableCell>().ElementAt(3).Append(new Paragraph(new Run(new Text("Test3"))));
                                         rowCopy.Descendants<TableCell>().ElementAt(4).Append(new Paragraph(new Run(new Text("Test4"))));
                                         rowCopy.Descendants<TableCell>().ElementAt(5).Append(new Paragraph(new Run(new Text("Test5"))));
                                         TabelaZapisnik.AppendChild(rowCopy);
                                         // Remove the empty placeholder row from the table.
                                         TabelaZapisnik.RemoveChild(Red);
    
                                         //closing WordprocessingDocument automatically saves the document
                                     }
                                newItem["ID ПонудеСмештај"] = id;
                                newItem["ID Субјект"] = idsubjekt;
                                newItem.Update();
                                file.Update();
                                file.ParentFolder.Files.Add(destFile, memStr, true);
                                 }
                                     //OpenXml kreiranje dokumenata - kraj
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.