使用 MergeFields 操作带流的 word 文档

Use MergeFields to manipulate a word document with stream

这是复制到本地路径的旧代码,但现在我需要将文件保存在 SharePoint 上。我如何使用流并将流写入文件。

File.Copy(oTemplatePath, destinationPath, true);

        using (WordprocessingDocument document = WordprocessingDocument.Open(destinationPath, true))
        {




            document.GetMergeFields("reference_number").ReplaceWithText(refrenceNumber);
            document.MainDocumentPart.Document.Save();


            for (int i = 0; i < newDoc.jsonFields.Count; i++)
            {
                if (newDoc.jsonFields[i].type == "date")
                {
                    document.GetMergeFields(newDoc.jsonFields[i].controlName).ReplaceWithText(DateTime.Parse(newDoc.jsonFields[i].data).ToShortDateString());
                    document.MainDocumentPart.Document.Save();
                }
                else
                {
                    document.GetMergeFields(newDoc.jsonFields[i].controlName).ReplaceWithText(newDoc.jsonFields[i].data);
                    document.MainDocumentPart.Document.Save();

                }



            }
            //document.GetMergeFields(newDoc.jsonFields[i].controlName).ReplaceWithText(newDoc.jsonFields[i].data);
            //document.MainDocumentPart.Document.Save();


        }

您可以保存到本地临时文件夹

string tempDocx = Path.Combine(Path.GetTempPath(), fileName);
logger.Trace($"Creating Word document {tempDocx}");
File.Delete(tempDocx);
File.Copy("Template.docx", tempDocx);

然后上传到 SharePoint,这里使用 FileStream

using (IO.FileStream fs = new IO.FileStream(tempDocx, IO.FileMode.Open))
{
    List documentsList = clientContext.Web.Lists.GetByTitle(libTitle);
    clientContext.Load(documentsList.RootFolder);
    clientContext.ExecuteQuery();

    var fileCreationInformation = new FileCreationInformation();

    //Assign to content byte[] i.e. documentStream
    fileCreationInformation.ContentStream = fs;

    //Allow owerwrite of document
    fileCreationInformation.Overwrite = true;

    //Upload URL
    fileCreationInformation.Url = documentsList.RootFolder.ServerRelativeUrl + "/" + IO.Path.GetFileName(tempDocx);

    uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);
    clientContext.Load(uploadFile);

    clientContext.ExecuteQuery();
}