动态创建openxml文档

时间:2017-07-31 11:01:18

标签: c# asp.net openxml openxml-sdk

我正在尝试动态构建一个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

1 个答案:

答案 0 :(得分:2)

尝试在using

的末尾添加此行
doc.MainDocumentPart.Document.Save();
doc.Close();
fileBytes = stream.ToArray();

并保存文件:

File.WriteAllBytes(string path, fileBytes)