动态创建openxml文档

问题描述 投票:1回答:1

我正在尝试动态构建一个openxml文档,基本上我有一些类负责创建我的文档的各个部分(表,段......)然后我需要另一个类来构建我的文档,在我的情况下我称之为doc ,我的其他课程是docTable,docRun ......

所以此刻我有这个:

    DocRun projectNameTitle = new DocRun();
    Run projectNameTxt = disclaimerDescription.createParagraph(document.projectName, SUBTITLECOLOR, FONTSIZESUBTITLE,FONTTYPE);

    DocRun dateParagraph = new DocRun();
    Run dateTxt = disclaimerDescription.createParagraph(date, PARAGRAPHTITLECOLOR, DATEFONTSIZE, DEFAULTFONT);

    Doc simpleDoc = new Doc();
    simpleDoc.CreateDoc(dateParagraph, projectNameTitle);

段落构建正确我现在只需将其设置为doc的主体,doc类进入的位置,传递的参数应该负责按照传递的顺序构建文档。

这是我的班级负责构建文档:

using System.Web.Hosting;

namespace openXml
{
    public class Doc
    {
        public const String DOCUMENTSLOCATION = "~/Files"; // default documents location
        public void CreateDoc(params object[] document)
        {
            var stream = new MemoryStream();
            using (WordprocessingDocument doc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true))
            {
                MainDocumentPart mainPart = doc.AddMainDocumentPart();

                new Document(new Body()).Save(mainPart);

                Body body = mainPart.Document.Body;

                foreach (var docSections in document)
                {
                    body.Append(new Paragraph(new ParagraphProperties(),
                   new Run((Run)docSections)));
                }
            }
            stream.Seek(0, SeekOrigin.Begin);
            Directory.CreateDirectory(HostingEnvironment.MapPath(DOCUMENTSLOCATION));
            System.IO.File.WriteAllBytes(HostingEnvironment.MapPath("~/Files/test5.docx"), stream.ToArray());
        }
    }
}

我在这里遇到了一些麻烦,因为我不知道我是否正在通过运行或其他事情,我怎么能迭代传递的项目列表并在这种情况下附加到文档中,我不知道我是什么在这里做错了,文档没有被创建:S

c# asp.net openxml openxml-sdk
1个回答
2
投票

尝试在using的末尾添加这些行

doc.MainDocumentPart.Document.Save();
doc.Close();
fileBytes = stream.ToArray();

并保存文件:

File.WriteAllBytes(string path, fileBytes)
© www.soinside.com 2019 - 2024. All rights reserved.