动态创建openxml文档 [英] Create openxml document dynamically

查看:111
本文介绍了动态创建openxml文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图动态地构建一个openxml文档,基本上我有一些类负责创建文档的各个部分(表格,段落...),然后我需要另一个类来构建我的文档,就我而言叫做doc,我的其他类是docTable,docRun ...

I am trying to build a openxml document dynamically, basically I have some classes responsible for creating the sections of my document (tables,paragraph...) then I need to have another class that builds my document, in my case I called it doc, and my other classes are 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类进入的地方,传递的参数应负责按照传递的顺序构建文档.

the paragraph builds correctly I just need to set it to the body of the doc at the moment, there is where the doc class enters, the parameters passed should be responsible to build the document in the order they are passed.

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

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

I am having some troubles here, because I don't know if I am passing a run or other thing, how can I iterate over a list of items passed and append to the document in this case, I don't know what I am doing wrong here, the document doesn't get created :S

推荐答案

尝试在using

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

然后像这样保存文件:

File.WriteAllBytes(string path, fileBytes)

这篇关于动态创建openxml文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆