使用MergeFields来处理带有流的word文档

时间:2017-11-17 16:40:51

标签: c# .net openxml-sdk

这是复制到本地路径的旧代码,但现在我需要将文件保存在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();


        }

1 个答案:

答案 0 :(得分:0)

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

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

然后使用FileStream

上传到SharePoint
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();
}