【问题标题】:Create openxml document dynamically动态创建openxml文档
【发布时间】:2017-07-31 11:01:17
【问题描述】:

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

    尝试在using末尾添加这一行

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

    然后像这样保存文件:

    File.WriteAllBytes(string path, fileBytes)
    

    【讨论】:

    • 它有效,但我有一个问题,如果我创建一个图像,我需要将它传递给主要部分,我想要那个主要部分,我的意思是在文档类方面,我真的需要图片的mainpart参数?
    • 将此作为另一个问题提出。答案将帮助遇到同样问题的其他人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    • 2014-10-18
    • 2011-12-19
    • 2013-08-19
    相关资源
    最近更新 更多