Search code examples
c#openxml

Open XML SDK: How to get a valid Word document for WordprocessingDocument.Open


For unit testing purposes, I would like to generate some sample data to be stored as a stream in the dataToImport variable in the following statement:

WordprocessingDocument.Open(dataToImport, false);

Does anyone know how to create a decent set of sample data?


Solution

  • You could potentially use something like the following:

    using (WordprocessingDocument wpd = WordprocessingDocument.Open(filename, false) 
    {
        wpd.MainDocumentPart.Document.Body.Append(GenerateParagraph(...text ...);
    }
    
    
    private Paragraph GenerateParagraph(string input) 
    {
        Paragraph paragraph1 = new Paragraph();
        Run run1 = new Run();
        Break break1 = new Break() { Type = BreakValues.Page };
        Text txt = new Text() { Space = SpaceProcessingModeValues.Preserve };
        txt.Text = input;
        run1.Append(break1);
        run1.Append(txt);
        paragraph1.Append(run1);
        return paragraph1;
    
    }
    

    The value of the ...text... itself could come from any file using FileInputStream objects.

    Hope it helps!