2017-07-31 141 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