Working with Open XML

Open XML can be used for working with spreadsheet, charts , presentation and word processing. As the root for Word, Excel is XML , we can manipulate the XML to achieve the required.
You will need to download OPEN XML SDK 2.5 for the below demo.

using (WordprocessingDocument doc = WordprocessingDocument.Create(document, WordprocessingDocumentType.Document))
            {               
                MainDocumentPart mainPart = doc.AddMainDocumentPart();   
                ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);                
                string imageID = mainPart.GetIdOfPart(imagePart);
                using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(imagePart.GetStream()))
                {
                    writer.Write(System.IO.File.ReadAllBytes(@"..\..\TestFull.png"));
                    writer.Flush();
                }
                mainPart.Document = new Document(new Body());
                Paragraph par;
                
                doc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(GetDrawing(imageID, mainPart.GetIdOfPart(imagePart)))));
                foreach (var str in data)
                {                   
                    //par = CreateParagraph(str, style);
                    if (count == 0)
                    {
                        par = CreatePragaraphWholeBoldCenter(str);
                        mainPart.Document.Body.Append(par);
                        count++;
                        continue;
                    }
                    else if (count == 4)
                    {
                        par = CreatePragaraphWholeBoldLeft(str);
                        mainPart.Document.Body.Append(par);

                        Table a = WDAddTable(document, cust);
                        mainPart.Document.Body.Append(a);
                        mainPart.Document.Body.Append(CreatePragaraphWholeBoldLeft(""));
                        count++;
                        continue;
                    }
                    else if (count == 5)
                    {
                        par = CreatePragaraphWholeBoldLeft(str);
                        mainPart.Document.Body.Append(par);

                        Table a = WDAddSingleTable(document, test);
                        mainPart.Document.Body.Append(a);
                        mainPart.Document.Body.Append(CreatePragaraphWholeBoldLeft(""));
                        count++;
                        continue;
                    }
                    else if (count == 6)
                    {
                        par = CreatePragaraphWholeBoldLeft(str);                        
                        mainPart.Document.Body.Append(par);

                        //Table a = WDAddSingleTable(document, new string[]{specialreq});
                        //mainPart.Document.Body.Append(a);
                        par = CreatePragaraphWholeLeft(specialreq);
                        mainPart.Document.Body.Append(par);
                        
                        count++;
                        continue;
                    }
                    else if (count == 7)
                    {
                        par = CreatePragaraphWholeBoldLeft(str);
                        mainPart.Document.Body.Append(par);

                        par = CreatePragaraphWholeLeft(source);
                        mainPart.Document.Body.Append(par);
                        count++;
                        continue;
                    }
                    else if (count == 8)
                    {
                        par = CreatePragaraphWholeBoldLeft(str);
                        mainPart.Document.Body.Append(par);

                        par = CreatePragaraphWholeLeft(detailsofcharges);
                        mainPart.Document.Body.Append(par);
                        count++;
                        continue;
                    }
                    else
                    {
                        par = CreatePragaraphWholeBoldLeft(str);
                        mainPart.Document.Body.Append(par);
                        count++;
                        continue;
                    }
                    
                }
            }

For Creating Bordered Paragraph .

  private Paragraph CreateBorderParagraph(string str)
        {
            Paragraph par = new Paragraph(new ParagraphProperties());
            //new Run(new Text("Hello, world"))));

            par.ParagraphProperties.ParagraphBorders = new ParagraphBorders();
            par.ParagraphProperties.ParagraphBorders.LeftBorder = new LeftBorder();
            par.ParagraphProperties.ParagraphBorders.LeftBorder.Size = 24;
            par.ParagraphProperties.ParagraphBorders.LeftBorder.Val = BorderValues.Single;
            par.ParagraphProperties.ParagraphBorders.LeftBorder.Color = "4F81BD";

            par.ParagraphProperties.ParagraphBorders.RightBorder = new RightBorder();
            par.ParagraphProperties.ParagraphBorders.LeftBorder.Size = 24;
            par.ParagraphProperties.ParagraphBorders.LeftBorder.Val = BorderValues.Single;
            par.ParagraphProperties.ParagraphBorders.LeftBorder.Color = "4F81BD";

            par.ParagraphProperties.ParagraphBorders.BottomBorder = new BottomBorder();
            par.ParagraphProperties.ParagraphBorders.LeftBorder.Size = 24;
            par.ParagraphProperties.ParagraphBorders.LeftBorder.Val = BorderValues.Single;
            par.ParagraphProperties.ParagraphBorders.LeftBorder.Color = "4F81BD";

            par.ParagraphProperties.ParagraphBorders.TopBorder = new TopBorder();
            par.ParagraphProperties.ParagraphBorders.LeftBorder.Size = 24;
            par.ParagraphProperties.ParagraphBorders.LeftBorder.Val = BorderValues.Single;
            par.ParagraphProperties.ParagraphBorders.LeftBorder.Color = "4F81BD";


            par.Append(new Run(new Text(str)));

            return par;
        }

For creating Whole Bold Paragraph


 private Paragraph CreatePragaraphWholeBoldCenter(string str)
        {
            Paragraph par = new Paragraph(new ParagraphProperties(
						new Justification() { Val = JustificationValues.Center  }));
            Run run = par.AppendChild(new Run());
            RunProperties runProperties = run.AppendChild(new RunProperties());
            FontSize fontSize = new FontSize();
            fontSize.Val = "40";
            Bold bold = new Bold();
            runProperties.AppendChild(fontSize);
            runProperties.AppendChild(bold);
            // runProperties.AppendChild(id);
            run.AppendChild(new Text(str));
            return par;
        }

Creating Bold Paragraph with Left Alignment

    private Paragraph CreatePragaraphWholeBoldLeft(string str)
        {
            Paragraph par = new Paragraph(new ParagraphProperties(
                        new Justification() { Val = JustificationValues.Left }));

            Run run = par.AppendChild(new Run());
            RunProperties runProperties = run.AppendChild(new RunProperties());
            FontSize fontSize = new FontSize(); 
            fontSize.Val = "24";
            Bold bold = new Bold();

            runProperties.AppendChild(fontSize);
            runProperties.AppendChild(bold);          
            run.AppendChild(new Text(str));
           
            //par.Append(
            //   new Run(
            //       new RunProperties( new Bold()),
            //       new Text(str)
            //       ));

            return par;
        }


Add Image in the document


 public Drawing GetDrawing(string ImageId, string relationshipId)
        {
            var element =
                 new Drawing(
                     new DW.Inline(
                         new DW.Extent() { Cx = 5925623, Cy = 986712 },
                         new DW.EffectExtent()
                         {
                             LeftEdge = 0L,
                             TopEdge = 0L,
                             RightEdge = 0L,
                             BottomEdge = 0L
                         },
                         new DW.DocProperties()
                         {
                             Id = (UInt32Value)1U,
                             Name = "Picture 1"
                         },
                         new DW.NonVisualGraphicFrameDrawingProperties(
                             new A.GraphicFrameLocks() { NoChangeAspect = true }),
                         new A.Graphic(
                             new A.GraphicData(
                                 new PIC.Picture(
                                     new PIC.NonVisualPictureProperties(
                                         new PIC.NonVisualDrawingProperties()
                                         {
                                             Id = (UInt32Value)0U,
                                             Name = "TestFull.png"
                                         },
                                         new PIC.NonVisualPictureDrawingProperties()),
                                     new PIC.BlipFill(
                                         new A.Blip(
                                             new A.BlipExtensionList(
                                                 new A.BlipExtension()
                                                 {
                                                     Uri =
                                                       "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                                 })
                                         )
                                         {
                                             Embed = relationshipId,
                                             CompressionState =
                                             A.BlipCompressionValues.Print
                                         },
                                         new A.Stretch(
                                             new A.FillRectangle())),
                                     new PIC.ShapeProperties(
                                         new A.Transform2D(
                                             new A.Offset() { X = 0L, Y = 0L },
                                             new A.Extents() { Cx = 5925623, Cy = 986712 }),
                                         new A.PresetGeometry(
                                             new A.AdjustValueList()
                                         ) { Preset = A.ShapeTypeValues.Rectangle }))
                             ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                     )
                     {
                         DistanceFromTop = (UInt32Value)0U,
                         DistanceFromBottom = (UInt32Value)0U,
                         DistanceFromLeft = (UInt32Value)0U,
                         DistanceFromRight = (UInt32Value)0U,
                         EditId = "50D07946"
                     });
            return element;
        }

Add Table with Single Column


 public Table WDAddTable(string fileName, string[,] data)
        {

            

            Table table = new Table();

            TableProperties props = new TableProperties(
              new TableBorders(
                new TopBorder
                {
                    Val = new EnumValue<BorderValues>(BorderValues.Single),
                    Size = 12
                },
                new BottomBorder
                {
                    Val = new EnumValue<BorderValues>(BorderValues.Single),
                    Size = 12
                },
                new LeftBorder
                {
                    Val = new EnumValue<BorderValues>(BorderValues.Single),
                    Size = 12
                },
                new RightBorder
                {
                    Val = new EnumValue<BorderValues>(BorderValues.Single),
                    Size = 12
                },
                new InsideHorizontalBorder
                {
                    Val = new EnumValue<BorderValues>(BorderValues.Single),
                    Size = 12
                },
                new InsideVerticalBorder
                {
                    Val = new EnumValue<BorderValues>(BorderValues.Single),
                    Size = 12
                }));
            table.AppendChild<TableProperties>(props);

            if (data!=null)
            {
                for (var i = 0; i <= data.GetUpperBound(0); i++)
                {
                    var tr = new TableRow();
                    for (var j = 0; j <= data.GetUpperBound(1); j++)
                    {
                        var tc = new TableCell();
                        tc.Append(new Paragraph(new Run(new Text(data[i, j]))));
                        // Assume you want columns that are automatically sized.
                        //tc.Append(new TableCellProperties(
                        //  new TableCellWidth { Type = TableWidthUnitValues.Auto }));
                        tr.Append(tc);
                    }
                    table.Append(tr);
                } 
            }


            return table;



        }

Add Table with 2 Columns


public Table WDAddSingleTable(string fileName, string[] data)
        {
            Table table = new Table();

            TableProperties props = new TableProperties(
              new TableBorders(
                new TopBorder
                {
                    Val = new EnumValue<BorderValues>(BorderValues.Single),
                    Size = 12
                },
                new BottomBorder
                {
                    Val = new EnumValue<BorderValues>(BorderValues.Single),
                    Size = 12
                },
                new LeftBorder
                {
                    Val = new EnumValue<BorderValues>(BorderValues.Single),
                    Size = 12
                },
                new RightBorder
                {
                    Val = new EnumValue<BorderValues>(BorderValues.Single),
                    Size = 12
                },
                new InsideHorizontalBorder
                {
                    Val = new EnumValue<BorderValues>(BorderValues.Single),
                    Size = 12
                },
                new InsideVerticalBorder
                {
                    Val = new EnumValue<BorderValues>(BorderValues.Single),
                    Size = 12
                }));
            table.AppendChild<TableProperties>(props);

            if (data!=null)
            {
                for (var i = 0; i <= data.GetUpperBound(0); i++)
                {
                    var tr = new TableRow();

                    var tc = new TableCell();
                    tc.Append(new Paragraph(new Run(new Text(data[i]))));
                    // Assume you want columns that are automatically sized.
                    //tc.Append(new TableCellProperties(
                    //  new TableCellWidth { Type = TableWidthUnitValues.Auto }));
                    tr.Append(tc);

                    table.Append(tr);
                } 
            }


            return table;



        }

Leave a comment