2017-07-31 86 views
1

我想动态地创建一个openxml文档,基本上我有一些类可以创建我的文档(表,段落...)然后我需要有另一个类来构建我的文档,在我来说,我把它称为DOC,和我的其他类docTable,docRun ...动态创建openxml文档

所以此刻,我有这样的:

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

段落建立正确我只需要设置到目前文档的主体,文档类是进入的地方,传递的参数应该是respo无法按照传递的顺序构建文档。

这里是我的类RESPONSABLE为构建文档:

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

回答

2

尝试在using的末尾添加以下行

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

和保存文件这样的:

File.WriteAllBytes(string path, fileBytes) 
+0

它的工作,但我有一个问题,如果我创建了一个形象,我需要它传递mainpart,我想,mainpart,因为它是,我的意思是在doc类的一面,我真的需要图像的mainpart参数吗? –

+1

请问这是另一个问题。答案将有助于其他遇到同样问题的人。 – Taterhead