C# : Editing/saving/Sending a docx document

谁都会走 提交于 2019-12-25 00:01:24

问题


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());
    }


来源:https://stackoverflow.com/questions/52894075/c-sharp-editing-saving-sending-a-docx-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!