Ejemplo n.º 1
0
 internal Relationship ToRelationship(RelationshipCounter relationshipCounter)
 {
     return new Relationship(relationshipCounter)
         {
             Target = ToXmlFile(),
             Type = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings"
         };
 }
Ejemplo n.º 2
0
 internal Relationship ToRelationship(RelationshipCounter relationshipCounter)
 {
     return(new Relationship(relationshipCounter)
     {
         Target = ToXmlFile(),
         Type = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings"
     });
 }
Ejemplo n.º 3
0
 public XlsxWriterInternal(Workbook workbook)
 {
     _workbook            = workbook;
     _relationshipCounter = new RelationshipCounter();
     _sharedStrings       = new SharedStrings();
     _package             = new XlsxPackage();
     _styles = GetXlsxStyles();
 }
Ejemplo n.º 4
0
 public XlsxWriterInternal(Workbook workbook, CompressionOption compressionOption)
 {
     _workbook = workbook;
     _relationshipCounter = new RelationshipCounter();
     _sharedStrings = new SharedStrings();
     _package = new XlsxPackage { CompressionOption = compressionOption };
     _styles = GetXlsxStyles();
 }
Ejemplo n.º 5
0
 public XlsxWriterInternal(Workbook workbook, CompressionOption compressionOption)
 {
     _workbook            = workbook;
     _relationshipCounter = new RelationshipCounter();
     _sharedStrings       = new SharedStrings();
     _package             = new XlsxPackage {
         CompressionOption = compressionOption
     };
     _styles = GetXlsxStyles();
 }
Ejemplo n.º 6
0
            /// <summary>
            /// Generated the docProps/core.xml which contains author, creation date etc.
            /// </summary>
            /// <returns></returns>
            private static Relationship CreateCoreFileProperties(Workbook workbook,
                                                                 RelationshipCounter relationshipCounter)
            {
                var file = new XmlFile
                {
                    ContentType = "application/vnd.openxmlformats-package.core-properties+xml",
                    Path        = "docProps/core.xml"
                };

                var dc      = Namespaces.dc;
                var dcterms = Namespaces.dcterms;
                var xsi     = Namespaces.xsi;
                var cp      = Namespaces.coreProperties;

                var doc  = new XDocument();
                var root = new XElement(cp + "coreProperties",
                                        new XAttribute(XNamespace.Xmlns + "cp", cp),
                                        new XAttribute(XNamespace.Xmlns + "dc", dc),
                                        new XAttribute(XNamespace.Xmlns + "dcterms", dcterms),
                                        new XAttribute(XNamespace.Xmlns + "xsi", xsi)
                                        );

                if (!string.IsNullOrEmpty(workbook.Title))
                {
                    root.Add(new XElement(dc + "title", workbook.Title));
                }

                if (!string.IsNullOrEmpty(workbook.Author))
                {
                    root.Add(new XElement(dc + "creator", workbook.Author));
                    root.Add(new XElement(cp + "lastModifiedBy", workbook.Author));
                }

                root.Add(new XElement(dcterms + "created", DateTime.UtcNow,
                                      new XAttribute(xsi + "type", "dcterms:W3CDTF")));
                root.Add(new XElement(dcterms + "modified", DateTime.UtcNow,
                                      new XAttribute(xsi + "type", "dcterms:W3CDTF")));


                doc.Add(root);

                file.Content = doc;

                var rel = new Relationship(relationshipCounter)
                {
                    Target = file,
                    Type   = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"
                };

                return(rel);
            }
Ejemplo n.º 7
0
            /// <summary>
            /// Create the xl/worksheets/sheetX.xml file
            /// </summary>
            /// <param name="sheet"></param>
            /// <param name="sheetIndex"></param>
            /// <param name="relationshipCounter"></param>
            /// <param name="styles"></param>
            /// <param name="ignoredErrors"></param>
            /// <param name="sharedStrings"></param>
            /// <param name="sheetRels">If this worksheet needs an xl/worksheets/_rels/sheetX.xml.rels file</param>
            /// <returns></returns>
            private static Relationship CreateSheetFile(Worksheet sheet, int sheetIndex,
                                                        RelationshipCounter relationshipCounter, IList <XlsxCellStyle> styles,
                                                        XlsxIgnoredErrorCollection ignoredErrors, SharedStrings sharedStrings, out XmlFile sheetRels)
            {
                var rows = GetXlsxRows(sheet, styles, sharedStrings);

                var file = new XmlFile
                {
                    ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
                    Path        = "xl/worksheets/sheet" + sheetIndex + ".xml"
                };

                var doc = new XDocument(new XElement(Namespaces.workbook + "worksheet",
                                                     new XAttribute("xmlns", Namespaces.workbook),
                                                     new XAttribute(XNamespace.Xmlns + "r", Namespaces.relationship),
                                                     new XAttribute(XNamespace.Xmlns + "mc", Namespaces.mc),
                                                     new XAttribute(XNamespace.Xmlns + "x14ac", Namespaces.x14ac),
                                                     new XAttribute(XNamespace.Xmlns + "or", Namespaces.officeRelationships),
                                                     new XAttribute(Namespaces.mc + "Ignorable", "x14ac")
                                                     ));

                WriteSheetViews(sheet, doc);

                var sheetFormatPr = new XElement(Namespaces.workbook + "sheetFormatPr");

                sheetFormatPr.Add(new XAttribute("defaultRowHeight", 15));
                doc.Root?.Add(sheetFormatPr);

                if (sheet.ColumnWidths.Any())
                {
                    var cols = new XElement(Namespaces.workbook + "cols");
                    foreach (var cw in sheet.ColumnWidths)
                    {
                        var rowId = cw.Key + 1;
                        var col   = new XElement(Namespaces.workbook + "col",
                                                 new XAttribute("min", rowId),
                                                 new XAttribute("max", rowId),
                                                 new XAttribute("width", (decimal)cw.Value + ExcelColumnWidthDifference),
                                                 new XAttribute("customWidth", 1));
                        cols.Add(col);
                    }

                    doc.Root?.Add(cols);
                }

                var sheetData = new XElement(Namespaces.workbook + "sheetData");

                foreach (var row in rows.OrderBy(rk => rk.Key))
                {
                    var re = new XElement(Namespaces.workbook + "row", new XAttribute("r", row.Value.RowIndex));
                    foreach (var cell in row.Value.Cells)
                    {
                        var ce = new XElement(Namespaces.workbook + "c",
                                              new XAttribute("r", cell.Reference),
                                              new XAttribute("t", cell.CellType),
                                              new XAttribute("s", cell.StyleIndex));

                        ce.Add(cell.CellType == XlsxCellTypes.FormulaString
                            ? new XElement(Namespaces.workbook + "f", cell.Value)
                            : new XElement(Namespaces.workbook + "v", cell.Value));

                        re.Add(ce);
                    }

                    sheetData.Add(re);
                }

                doc.Root?.Add(sheetData);

                sheetRels = null;
                var hyperlinks = sheet.Cells.Where(c => c.Value != null && !string.IsNullOrEmpty(c.Value.Hyperlink))
                                 .ToList();

                if (hyperlinks.Count > 0)
                {
                    sheetRels = new XmlFile
                    {
                        Path        = "xl/worksheets/_rels/sheet" + sheetIndex + ".xml.rels",
                        ContentType = "application/vnd.openxmlformats-package.relationships+xml"
                    };

                    var hlRelsElem = new XElement(Namespaces.relationship + "Relationships");

                    var hlElem = new XElement(Namespaces.workbook + "hyperlinks");
                    for (int i = 0; i <= hyperlinks.Count - 1; i++)
                    {
                        string hyperLinkRelId = "rId" + (i + 1);

                        var link     = hyperlinks[i];
                        var linkElem = new XElement(Namespaces.workbook + "hyperlink",
                                                    new XAttribute("ref", link.Key.ToString()),
                                                    new XAttribute(Namespaces.officeRelationships + "id", hyperLinkRelId)
                                                    );
                        hlElem.Add(linkElem);

                        hlRelsElem.Add(new XElement(Namespaces.relationship + "Relationship",
                                                    new XAttribute("Id", hyperLinkRelId),
                                                    new XAttribute("Type",
                                                                   "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"),
                                                    new XAttribute("Target", link.Value.Hyperlink),
                                                    new XAttribute("TargetMode", "External")));
                    }

                    doc.Root?.Add(hlElem);
                    sheetRels.Content = new XDocument();
                    sheetRels.Content.Add(hlRelsElem);
                }

                var pageSetup = new XElement(Namespaces.workbook + "pageSetup");

                pageSetup.Add(new XAttribute("orientation",
                                             sheet.PageSetup.Orientation == Orientation.Portrait ? "portrait" : "landscape"));
                doc.Root?.Add(pageSetup);

                WritePageBreaks(sheet, doc);
                WriteIgnoredErrors(ignoredErrors, doc);

                file.Content = doc;
                var rel = new Relationship(relationshipCounter)
                {
                    Target = file,
                    Type   = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"
                };

                return(rel);
            }
Ejemplo n.º 8
0
            // ReSharper disable once MemberHidesStaticFromOuterClass
            internal static void Save(Workbook workbook, Stream outputStream, bool compress)
            {
                var relationshipCounter = new RelationshipCounter();
                var package             = new XlsxPackage();

                // Must be done before calling GetXlsxStyles as it may add styles
                foreach (var sheet in workbook.Sheets)
                {
                    HandleLargeNumbers(sheet);
                }

                ExtractWorkbookSpecialXmlParts(workbook, out var styles, out var ignoredErrors);
                var sharedStrings = new SharedStrings();

                // docProps/core.xml
                var cp = CreateCoreFileProperties(workbook, relationshipCounter);

                package.XmlFiles.Add(cp.Target);
                package.Relationships.Add(cp);

                // xl/styles.xml
                var stylesXml = StyleWriter.CreateStyleXml(styles);
                var stylesRel = new Relationship(relationshipCounter)
                {
                    Type   = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
                    Target = stylesXml
                };

                package.XmlFiles.Add(stylesXml);
                package.WorkbookRelationships.Add(stylesRel);

                // xl/worksheets/sheetX.xml
                var sheetPackageInfos = new List <SheetPackageInfo>();
                var i = 0;

                foreach (var sheet in workbook.Sheets)
                {
                    i++;
                    var rel = CreateSheetFile(sheet, i, relationshipCounter, styles, ignoredErrors[sheet],
                                              sharedStrings, out var sheetRels);
                    if (sheetRels != null)
                    {
                        package.XmlFiles.Add(sheetRels);
                    }

                    package.XmlFiles.Add(rel.Target);
                    package.WorkbookRelationships.Add(rel);

                    var sheetPackageInfo = new SheetPackageInfo
                    {
                        RelationshipId = rel.Id,
                        SheetId        = i,
                        SheetName      = sheet.Name
                    };
                    if (sheet.PageSetup.PrintRepeatColumns > 0)
                    {
                        sheetPackageInfo.RepeatCols = "'" + sheet.Name + "'!$A:$" +
                                                      CellAddressHelper.ColToReference(sheet.PageSetup.PrintRepeatColumns - 1);
                    }

                    if (sheet.PageSetup.PrintRepeatRows > 0)
                    {
                        sheetPackageInfo.RepeatRows = "'" + sheet.Name + "'!$1:$" + sheet.PageSetup.PrintRepeatRows;
                    }

                    sheetPackageInfos.Add(sheetPackageInfo);
                }

                // xl/sharedStrings.xml
                if (sharedStrings.Count > 0)
                {
                    var ssx = sharedStrings.ToRelationship(relationshipCounter);
                    package.XmlFiles.Add(ssx.Target);
                    package.WorkbookRelationships.Add(ssx);
                }

                // xl/workbook.xml
                var wb = CreateWorkbookFile(sheetPackageInfos, relationshipCounter);

                package.XmlFiles.Add(wb.Target);
                package.Relationships.Add(wb);

                // xl/_rels/workbook.xml.rels
                package.SaveToStream(outputStream, compress);
            }
Ejemplo n.º 9
0
            /// <summary>
            /// Create the xl/workbook.xml file and associated relationship
            /// </summary>
            /// <param name="sheetInfos"></param>
            /// <param name="relationshipCounter"></param>
            /// <returns></returns>
            private static Relationship CreateWorkbookFile(List <SheetPackageInfo> sheetInfos,
                                                           RelationshipCounter relationshipCounter)
            {
                var file = new XmlFile
                {
                    ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
                    Path        = "xl/workbook.xml"
                };

                var doc = new XDocument(new XElement(Namespaces.workbook + "workbook",
                                                     new XAttribute("xmlns", Namespaces.workbook),
                                                     new XAttribute(XNamespace.Xmlns + "r", Namespaces.workbookRelationship)
                                                     ));

                var sheets = new XElement(Namespaces.workbook + "sheets");

                foreach (var si in sheetInfos)
                {
                    sheets.Add(new XElement(Namespaces.workbook + "sheet",
                                            new XAttribute("name", si.SheetName),
                                            new XAttribute("sheetId", si.SheetId),
                                            new XAttribute(Namespaces.workbookRelationship + "id", si.RelationshipId)
                                            ));
                }

                doc.Root?.Add(sheets);

                var repeatInfos = sheetInfos
                                  .Where(si => !string.IsNullOrEmpty(si.RepeatRows) || !string.IsNullOrEmpty(si.RepeatCols))
                                  .OrderBy(si => si.SheetId).ToList();

                if (repeatInfos.Count > 0)
                {
                    var dne = new XElement(Namespaces.workbook + "definedNames");
                    foreach (var re in repeatInfos)
                    {
                        var de = new XElement(Namespaces.workbook + "definedName",
                                              new XAttribute("name", "_xlnm.Print_Titles"),
                                              new XAttribute("localSheetId", re.SheetId - 1)
                                              );

                        if (!string.IsNullOrEmpty(re.RepeatCols) && !string.IsNullOrEmpty(re.RepeatRows))
                        {
                            de.Add(new XText(re.RepeatCols + "," + re.RepeatRows));
                        }
                        else if (!string.IsNullOrEmpty(re.RepeatCols))
                        {
                            de.Add(new XText(re.RepeatCols));
                        }
                        else if (!string.IsNullOrEmpty(re.RepeatRows))
                        {
                            de.Add(new XText(re.RepeatRows));
                        }

                        dne.Add(de);
                    }

                    doc.Root?.Add(dne);
                }

                file.Content = doc;

                var rel = new Relationship(relationshipCounter)
                {
                    Type   = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
                    Target = file
                };

                return(rel);
            }