none
How to set page orientation on a newly created spreadsheet in open XML? RRS feed

  • Question

  • I am generating a spreadsheet using c# and Open XML. Need help on:

    1. Setting the page orientation based on user selection.

    2. Put image on a page header.

    Please help.

    Thanks,

    Shishir. 

    Monday, May 30, 2011 5:50 PM

Answers

  • Hi Shishir,

    As for the first problem, you can reference the following code snippets to set or change the page orientation:

    using System.Linq;
    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Wordprocessing;
     
    namespace ChangePrintOrientation
    {
      class Program
      {
        static void Main(string[] args)
        {
          WDSetPrintOrientation(@"Orientation.docx"PageOrientationValues.Landscape);
        }
     
        // Given a document name, set the print orientation for the all the sections of the document.
        public static void WDSetPrintOrientation(
          string fileName, PageOrientationValues newOrientation)
        {
          using (var document = WordprocessingDocument.Open(fileName, true))
          {
            bool documentChanged = false;
     
            var docPart = document.MainDocumentPart;
            var sections = docPart.Document.Descendants<SectionProperties>();
     
            foreach (SectionProperties sectPr in sections)
            {
              bool pageOrientationChanged = false;
     
              PageSize pgSz = sectPr.Descendants<PageSize>().FirstOrDefault();
              if (pgSz != null)
              {
                // No Orient property? Create it now. Otherwise, just set its value.
                // Assume that the default orientation is Portrait.
                if (pgSz.Orient == null)
                {
                  // Need to create the attribute. You do not need to 
                  // create the Orient property if the property doesn't already
                  // exist, and you are setting it to Portrait. That's the default value.
                  if (newOrientation != PageOrientationValues.Portrait)
                  {
                    pageOrientationChanged = true;
                    documentChanged = true;
                    pgSz.Orient = new EnumValue<PageOrientationValues>(newOrientation);
                  }
                }
                else
                {
                  // The Orient property exists, but its value
                  // is different than the new value.
                  if (pgSz.Orient.Value != newOrientation)
                  {
                    pgSz.Orient.Value = newOrientation;
                    pageOrientationChanged = true;
                    documentChanged = true;
                  }
                }
     
                if (pageOrientationChanged)
                {
                  // Changing the orientation isn't enough. You must also change the page size.
                  var width = pgSz.Width;
                  var height = pgSz.Height;
                  pgSz.Width = height;
                  pgSz.Height = width;
     
                  PageMargin pgMar = sectPr.Descendants<PageMargin>().FirstOrDefault();
                  if (pgMar != null)
                  {
     
                    // Rotate margins. Printer settings control how far you 
                    // rotate when switching to landscape mode. Not having those
                    // settings, this code rotates 90 degrees. You could easily
                    // modify this behavior, or make it a parameter for the 
                    // procedure.
     
                    var top = pgMar.Top.Value;
                    var bottom = pgMar.Bottom.Value;
                    var left = pgMar.Left.Value;
                    var right = pgMar.Right.Value;
     
                    pgMar.Top = new Int32Value((int)left);
                    pgMar.Bottom = new Int32Value((int)right);
                    pgMar.Left = new UInt32Value((uint)System.Math.Max(0, bottom));
                    pgMar.Right = new UInt32Value((uint)System.Math.Max(0, top));
                  }
                }
              }
            }
            if (documentChanged)
            {
              docPart.Document.Save();
            }
          }
        }
     
      }
    }
    

    As for the second problem, I think the following method can give you some hint:

     // Generates content of headerPart1.
            private void GenerateHeaderPart1Content(HeaderPart headerPart1)
            {
                Header header1 = new Header() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
                header1.AddNamespaceDeclaration("wpc""http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
                header1.AddNamespaceDeclaration("mc""http://schemas.openxmlformats.org/markup-compatibility/2006");
                header1.AddNamespaceDeclaration("o""urn:schemas-microsoft-com:office:office");
                header1.AddNamespaceDeclaration("r""http://schemas.openxmlformats.org/officeDocument/2006/relationships");
                header1.AddNamespaceDeclaration("m""http://schemas.openxmlformats.org/officeDocument/2006/math");
                header1.AddNamespaceDeclaration("v""urn:schemas-microsoft-com:vml");
                header1.AddNamespaceDeclaration("wp14""http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
                header1.AddNamespaceDeclaration("wp""http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
                header1.AddNamespaceDeclaration("w10""urn:schemas-microsoft-com:office:word");
                header1.AddNamespaceDeclaration("w""http://schemas.openxmlformats.org/wordprocessingml/2006/main");
                header1.AddNamespaceDeclaration("w14""http://schemas.microsoft.com/office/word/2010/wordml");
                header1.AddNamespaceDeclaration("wpg""http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
                header1.AddNamespaceDeclaration("wpi""http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
                header1.AddNamespaceDeclaration("wne""http://schemas.microsoft.com/office/word/2006/wordml");
                header1.AddNamespaceDeclaration("wps""http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
     
                Paragraph paragraph2 = new Paragraph() { RsidParagraphAddition = "00FF150A", RsidRunAdditionDefault = "00FF150A" };
     
                ParagraphProperties paragraphProperties1 = new ParagraphProperties();
                ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "a3" };
     
                paragraphProperties1.Append(paragraphStyleId1);
                BookmarkStart bookmarkStart1 = new BookmarkStart() { Name = "_GoBack", Id = "0" };
     
                Run run2 = new Run();
     
                RunProperties runProperties2 = new RunProperties();
                NoProof noProof1 = new NoProof();
     
                runProperties2.Append(noProof1);
     
                Drawing drawing1 = new Drawing();
     
                Wp.Inline inline1 = new Wp.Inline() { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U };
                Wp.Extent extent1 = new Wp.Extent() { Cx = 5486400L, Cy = 4114800L };
                Wp.EffectExtent effectExtent1 = new Wp.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L };
                Wp.DocProperties docProperties1 = new Wp.DocProperties() { Id = (UInt32Value)1U, Name = "图片 1" };
     
                Wp.NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties1 = new Wp.NonVisualGraphicFrameDrawingProperties();
     
                A.GraphicFrameLocks graphicFrameLocks1 = new A.GraphicFrameLocks() { NoChangeAspect = true };
                graphicFrameLocks1.AddNamespaceDeclaration("a""http://schemas.openxmlformats.org/drawingml/2006/main");
     
                nonVisualGraphicFrameDrawingProperties1.Append(graphicFrameLocks1);
     
                A.Graphic graphic1 = new A.Graphic();
                graphic1.AddNamespaceDeclaration("a""http://schemas.openxmlformats.org/drawingml/2006/main");
     
                A.GraphicData graphicData1 = new A.GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" };
     
                Pic.Picture picture1 = new Pic.Picture();
                picture1.AddNamespaceDeclaration("pic""http://schemas.openxmlformats.org/drawingml/2006/picture");
     
                Pic.NonVisualPictureProperties nonVisualPictureProperties1 = new Pic.NonVisualPictureProperties();
                Pic.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Pic.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = "Jellyfish.jpg" };
                Pic.NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties1 = new Pic.NonVisualPictureDrawingProperties();
     
                nonVisualPictureProperties1.Append(nonVisualDrawingProperties1);
                nonVisualPictureProperties1.Append(nonVisualPictureDrawingProperties1);
     
                Pic.BlipFill blipFill1 = new Pic.BlipFill();
     
                A.Blip blip1 = new A.Blip() { Embed = "rId1" };
     
                A.BlipExtensionList blipExtensionList1 = new A.BlipExtensionList();
     
                A.BlipExtension blipExtension1 = new A.BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" };
     
                A14.UseLocalDpi useLocalDpi1 = new A14.UseLocalDpi() { Val = false };
                useLocalDpi1.AddNamespaceDeclaration("a14""http://schemas.microsoft.com/office/drawing/2010/main");
     
                blipExtension1.Append(useLocalDpi1);
     
                blipExtensionList1.Append(blipExtension1);
     
                blip1.Append(blipExtensionList1);
     
                A.Stretch stretch1 = new A.Stretch();
                A.FillRectangle fillRectangle1 = new A.FillRectangle();
     
                stretch1.Append(fillRectangle1);
     
                blipFill1.Append(blip1);
                blipFill1.Append(stretch1);
     
                Pic.ShapeProperties shapeProperties1 = new Pic.ShapeProperties();
     
                A.Transform2D transform2D1 = new A.Transform2D();
                A.Offset offset1 = new A.Offset() { X = 0L, Y = 0L };
                A.Extents extents1 = new A.Extents() { Cx = 5486400L, Cy = 4114800L };
     
                transform2D1.Append(offset1);
                transform2D1.Append(extents1);
     
                A.PresetGeometry presetGeometry1 = new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle };
                A.AdjustValueList adjustValueList1 = new A.AdjustValueList();
     
                presetGeometry1.Append(adjustValueList1);
     
                shapeProperties1.Append(transform2D1);
                shapeProperties1.Append(presetGeometry1);
     
                picture1.Append(nonVisualPictureProperties1);
                picture1.Append(blipFill1);
                picture1.Append(shapeProperties1);
     
                graphicData1.Append(picture1);
     
                graphic1.Append(graphicData1);
     
                inline1.Append(extent1);
                inline1.Append(effectExtent1);
                inline1.Append(docProperties1);
                inline1.Append(nonVisualGraphicFrameDrawingProperties1);
                inline1.Append(graphic1);
     
                drawing1.Append(inline1);
     
                run2.Append(runProperties2);
                run2.Append(drawing1);
                BookmarkEnd bookmarkEnd1 = new BookmarkEnd() { Id = "0" };
     
                paragraph2.Append(paragraphProperties1);
                paragraph2.Append(bookmarkStart1);
                paragraph2.Append(run2);
                paragraph2.Append(bookmarkEnd1);
     
                header1.Append(paragraph2);
     
                headerPart1.Header = header1;
            }

    Hope this can help you and just feel free to follow up after you have tried.

    Best Regards, 

     

     

     


    Bruce Song [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Bruce Song Tuesday, June 21, 2011 1:48 PM
    Friday, June 3, 2011 9:48 AM