C# : Editing/saving/Sending a docx document

2019-08-26 00:29发布

问题:

Been strugling with a lot of problems. Using OpenXML on a ASP.NET Core server, I want to create a new docx document based on a template one. Once this document is fully saved, I want it to be sent to my client so he can download it directly. Here's my code :

public IActionResult Post([FromBody] Consultant consultant)
    {
            using (Stream templateStream = new MemoryStream(Properties.Resources.templateDossierTech))
            using (WordprocessingDocument template =
                WordprocessingDocument.Open(templateStream, false))
            {

                string fileName = environment.WebRootPath + @"\Resources\"+ consultant.FirstName + "_" + consultant.LastName + ".docx";
                WordprocessingDocument dossierTechniqueDocument =
                    WordprocessingDocument.Create(fileName,
                        WordprocessingDocumentType.Document);
                foreach (var part in template.Parts)
                {
                    dossierTechniqueDocument.AddPart(part.OpenXmlPart, part.RelationshipId);
                }

                var body = dossierTechniqueDocument.MainDocumentPart.Document.Body;
                var paras = body.Elements();

                foreach (var para in paras)
                {
                    foreach (var run in para.Elements())
                    {
                        foreach (var text in run.Elements())
                        {
                            if (text.InnerText.Contains("{{prenom}}"))
                            {
                                var t = new Text(text.InnerText.Replace("{{prenom}}", consultant.FirstName));
                                run.RemoveAllChildren<Text>();
                                run.AppendChild(t);
                            }

                        }
                    }
                }
                dossierTechniqueDocument.MainDocumentPart.Document.Save();
                dossierTechniqueDocument.Close();
                var cd = new System.Net.Mime.ContentDisposition
                {
                    FileName = consultant.FirstName + "_" + consultant.LastName + ".docx",
                    Inline = true
                };

                Response.Headers.Add("Content-Disposition", cd.ToString());

                Response.Headers.Add("X-Content-Type-Options", "nosniff");
                return File(System.IO.File.ReadAllBytes(fileName),"application/vnd.openxmlformats-officedocument.wordprocessingml.document","Dossier Technique");
        }
    }

As a first look, it looks like is saving well but when I try to open it on word, it says that it is corrupted for some reason. That's the same problem when I try to send it. Once it's sent my client doesn't download it (Ajax query). Do anyone of you have any idea how to fix it ?

回答1:

Here is the function which creates a document from a template:

static void GenerateDocumentFromTemplate(string inputPath, string outputPath)
    {
        MemoryStream documentStream;
        using (Stream stream = File.OpenRead(inputPath))
        {
            documentStream = new MemoryStream((int)stream.Length);
            CopyStream(stream, documentStream);
            documentStream.Position = 0L;
        }

        using (WordprocessingDocument template = WordprocessingDocument.Open(documentStream, true))
        {
            template.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
            MainDocumentPart mainPart = template.MainDocumentPart;
            mainPart.DocumentSettingsPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
               new Uri(inputPath, UriKind.Absolute));

            mainPart.Document.Save();
        }


        File.WriteAllBytes(outputPath, documentStream.ToArray());
    }