Esempio n. 1
0
        public void ExtractMasters(string fileName)
        {
            var source = new PmlDocument(Path.Combine(SourceDirectory, fileName));
            int numberOfMasters;

            using (var stream = new OpenXmlMemoryStreamDocument(source))
            {
                using var doc1  = stream.GetPresentationDocument();
                numberOfMasters = doc1.PresentationPart.SlideMasterParts.Count();
            }


            var onlyMaster =
                PresentationBuilder.BuildPresentation(
                    new List <SlideSource> {
                new SlideSource(source, 0, 0, true)
            });

            onlyMaster.FileName = fileName.Replace(".pptx", "_masterOnly.pptx");
            onlyMaster.SaveAs(Path.Combine(TargetDirectory, onlyMaster.FileName));

            using var streamDoc = new OpenXmlMemoryStreamDocument(onlyMaster);
            using var resDoc    = streamDoc.GetPresentationDocument();

            Assert.Empty(resDoc.PresentationPart.SlideParts);
            Assert.Equal(numberOfMasters, resDoc.PresentationPart.SlideMasterParts.Count());
        }
        public static IEnumerable <PmlDocument> PublishSlides(PresentationDocument srcDoc, string fileName)
        {
            var slideList = srcDoc.PresentationPart.GetXDocument().Root.Descendants(P.sldId).ToList();

            for (var slideNumber = 0; slideNumber < slideList.Count; slideNumber++)
            {
                using var streamDoc = OpenXmlMemoryStreamDocument.CreatePresentationDocument();
                using (var output = streamDoc.GetPresentationDocument(new OpenSettings {
                    AutoSave = false
                }))
                {
                    ExtractSlide(srcDoc, slideNumber, output);

                    var slidePartId = slideList.ElementAt(slideNumber).Attribute(R.id)?.Value;
                    var slidePart   = (SlidePart)srcDoc.PresentationPart.GetPartById(slidePartId);
                    output.PackageProperties.Title = PresentationBuilderTools.GetSlideTitle(slidePart);
                }

                var slideDoc = streamDoc.GetModifiedPmlDocument();
                if (!string.IsNullOrWhiteSpace(fileName))
                {
                    slideDoc.FileName =
                        Regex.Replace(fileName, ".pptx", $"_{slideNumber + 1:000}.pptx", RegexOptions.IgnoreCase);
                }

                yield return(slideDoc);
            }
        }
Esempio n. 3
0
        protected override void EndProcessing()
        {
            if (!File.Exists(outputPath) || ShouldProcess(outputPath, "Export-OpenXmlSpreadsheet"))
            {
                using (OpenXmlMemoryStreamDocument streamDoc = OpenXmlMemoryStreamDocument.CreateSpreadsheetDocument())
                {
                    using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument())
                    {
                        if (processedObjects.Count > 0)
                        {
                            List <string> headerList = new List <string>();
                            foreach (PSPropertyInfo propertyInfo in processedObjects[0].Properties)
                            {
                                headerList.Add(propertyInfo.Name.ToUpper());
                            }

                            // Stores into a matrix all properties of objects passed as parameter
                            int        rowLength   = headerList.Count;
                            int        rowCount    = processedObjects.Count;
                            string[][] valueMatrix = new string[rowCount][];

                            int currentRow = 0, currentColumn = 0;
                            foreach (PSObject obj in processedObjects)
                            {
                                currentColumn           = 0;
                                valueMatrix[currentRow] = new string[rowLength];
                                foreach (PSPropertyInfo propertyInfo in obj.Properties)
                                {
                                    try
                                    {
                                        if (propertyInfo.Value != null)
                                        {
                                            valueMatrix[currentRow][currentColumn] = propertyInfo.Value.ToString();
                                        }
                                    }
                                    // Suppress errors on properties that cannot be read, but write the information to debug output.
                                    catch (GetValueInvocationException e)
                                    {
                                        WriteDebug(string.Format(CultureInfo.InvariantCulture, "Exception ({0}) at Object {1}, property {2}", e.Message, currentRow, currentColumn));
                                    }
                                    currentColumn++;
                                }
                                currentRow++;
                            }
                            if (displayChart)
                            {
                                SpreadsheetDocumentManager.Create(document, headerList, valueMatrix, chartType, headerColumn, columnsToChart, initialRow);
                            }
                            else
                            {
                                SpreadsheetDocumentManager.Create(document, headerList, valueMatrix, initialRow);
                            }
                        }
                    }
                    OpenXmlPowerToolsDocument output = streamDoc.GetModifiedDocument();
                    output.FileName = outputPath;
                    OutputDocument(output);
                }
            }
        }
        private static void Main()
        {
            DateTime n      = DateTime.Now;
            var      tempDi = new DirectoryInfo(
                $"ExampleOutput-{n.Year - 2000:00}-{n.Month:00}-{n.Day:00}-{n.Hour:00}{n.Minute:00}{n.Second:00}");

            tempDi.Create();

            var solarSystemDoc = new WmlDocument("../../../solar-system.docx");

            using var streamDoc = new OpenXmlMemoryStreamDocument(solarSystemDoc);
            using WordprocessingDocument solarSystem = streamDoc.GetWordprocessingDocument();
            XElement root = solarSystem.MainDocumentPart.GetXElement();

            // Get children elements of the <w:body> element, ignoring the w:sectPr element.
            IEnumerable <XElement> q1 = root
                                        .Elements(W.body)
                                        .Elements()
                                        .Where(e => e.Name != W.sectPr);

            // Project collection of tuples containing element and type.
            var q2 = q1.Select(e => new
            {
                Element             = e,
                KeyForGroupAdjacent = e.Name.LocalName switch
                {
                    nameof(W.sdt) => e.Element(W.sdtPr)?.Element(W.tag)?.Attribute(W.val)?.Value,
                    _ => ".NonContentControl"
                }
            });
Esempio n. 5
0
        public void Formulas1()
        {
            var sourceFile = GetFilePath("Formulas1/Formulas.xlsx");

            // Change sheet name in formulas
            using (var streamDoc = new OpenXmlMemoryStreamDocument(SmlDocument.FromFileName(sourceFile)))
            {
                using (var doc = streamDoc.GetSpreadsheetDocument())
                {
                    WorksheetAccessor.FormulaReplaceSheetName(doc, "Source", "'Source 2'");
                }
                streamDoc.GetModifiedSmlDocument().SaveAs(Path.Combine(TempDir, "FormulasUpdated.xlsx"));
            }

            // Change sheet name in formulas
            using (var streamDoc = new OpenXmlMemoryStreamDocument(SmlDocument.FromFileName(sourceFile)))
            {
                using (var doc = streamDoc.GetSpreadsheetDocument())
                {
                    var sheet = WorksheetAccessor.GetWorksheet(doc, "References");
                    WorksheetAccessor.CopyCellRange(doc, sheet, 1, 1, 7, 5, 4, 8);
                }
                streamDoc.GetModifiedSmlDocument().SaveAs(Path.Combine(TempDir, "FormulasCopied.xlsx"));
            }
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            var n      = DateTime.Now;
            var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second));

            tempDi.Create();

            // Change sheet name in formulas
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(
                       SmlDocument.FromFileName("../../Formulas.xlsx")))
            {
                using (SpreadsheetDocument doc = streamDoc.GetSpreadsheetDocument())
                {
                    WorksheetAccessor.FormulaReplaceSheetName(doc, "Source", "'Source 2'");
                }
                streamDoc.GetModifiedSmlDocument().SaveAs(Path.Combine(tempDi.FullName, "FormulasUpdated.xlsx"));
            }

            // Change sheet name in formulas
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(
                       SmlDocument.FromFileName("../../Formulas.xlsx")))
            {
                using (SpreadsheetDocument doc = streamDoc.GetSpreadsheetDocument())
                {
                    WorksheetPart sheet = WorksheetAccessor.GetWorksheet(doc, "References");
                    WorksheetAccessor.CopyCellRange(doc, sheet, 1, 1, 7, 5, 4, 8);
                }
                streamDoc.GetModifiedSmlDocument().SaveAs(Path.Combine(tempDi.FullName, "FormulasCopied.xlsx"));
            }
        }
Esempio n. 7
0
        public byte[] Run(List <PersonFiles> files)
        {
            var mergeXml = GetMergeXml(files);

            byte[] template = files.Where(p => p.Person == "/" && p.Name == "template.xlsx").Select(d => d.Data).FirstOrDefault();
            using (MemoryStream docInMemoryStream = new MemoryStream(template, 0, template.Length, true, true))
            {
                OpenXmlPowerToolsDocument docPowerTools = new OpenXmlPowerToolsDocument(string.Empty, docInMemoryStream);
                using (OpenXmlMemoryStreamDocument streamEmptyDoc = new OpenXmlMemoryStreamDocument(docPowerTools))
                {
                    SpreadsheetDocument excelTemplateDoc = streamEmptyDoc.GetSpreadsheetDocument();
                    excelTemplateDoc.WorkbookPart.Workbook.Sheets = new Sheets();

                    MergeDocument documentXml = mergeXml.Items.First();
                    foreach (MergeDocumentPart part in documentXml.Part)
                    {
                        byte[] byteArray = files.Where(p => p.Person == part.Name && p.Name == part.Id).Select(d => d.Data).FirstOrDefault();
                        using (MemoryStream docPartInMemoryStream = new MemoryStream(byteArray, 0, byteArray.Length, true, true))
                        {
                            OpenXmlPowerToolsDocument docPartPowerTools = new OpenXmlPowerToolsDocument(string.Empty, docPartInMemoryStream);
                            using (OpenXmlMemoryStreamDocument streamPartDoc = new OpenXmlMemoryStreamDocument(docPartPowerTools))
                            {
                                SpreadsheetDocument spreadSheetDocument = streamPartDoc.GetSpreadsheetDocument();
                                ExcelTools.MergeWorkSheets(excelTemplateDoc, spreadSheetDocument);

                                // Close the handle explicitly.
                                spreadSheetDocument.Close();
                            }
                        }
                    }

                    return(streamEmptyDoc.GetModifiedDocument().DocumentByteArray);
                }
            }
        }
        public byte[] Run(List <PersonFiles> files)
        {
            var                mergeXml          = GetMergeXml(files);
            MergeDocument      documentXml       = mergeXml.Items.First();
            IPresentationTools presentationTools = new PresentationTools();

            byte[] emptyTemplate = files.Where(p => p.Person == "/" && p.Name == "template.pptx").Select(d => d.Data).FirstOrDefault();
            using (MemoryStream emptyDocInMemoryStream = new MemoryStream(emptyTemplate, 0, emptyTemplate.Length, true, true))
            {
                OpenXmlPowerToolsDocument emptyDocPowerTools = new OpenXmlPowerToolsDocument(string.Empty, emptyDocInMemoryStream);
                using (OpenXmlMemoryStreamDocument streamEmptyDoc = new OpenXmlMemoryStreamDocument(emptyDocPowerTools))
                {
                    PresentationDocument emptyPresentation = streamEmptyDoc.GetPresentationDocument();
                    foreach (MergeDocumentPart part in documentXml.Part)
                    {
                        byte[] byteArray = files.Where(p => p.Person == part.Name && p.Name == part.Id).Select(d => d.Data).FirstOrDefault();
                        using (MemoryStream partDocInMemoryStream = new MemoryStream(byteArray, 0, byteArray.Length, true, true))
                        {
                            OpenXmlPowerToolsDocument partDocPowerTools = new OpenXmlPowerToolsDocument(string.Empty, partDocInMemoryStream);
                            using (OpenXmlMemoryStreamDocument streamDividedDoc = new OpenXmlMemoryStreamDocument(partDocPowerTools))
                            {
                                PresentationDocument templatePresentation = streamDividedDoc.GetPresentationDocument();
                                presentationTools.InsertSlidesFromTemplate(emptyPresentation, templatePresentation);
                            }
                        }
                    }

                    return(streamEmptyDoc.GetModifiedDocument().DocumentByteArray);
                }
            }
        }
        static void Main(string[] args)
        {
            // Change sheet name in formulas
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(
                       SmlDocument.FromFileName("../../Formulas.xlsx")))
            {
                using (SpreadsheetDocument doc = streamDoc.GetSpreadsheetDocument())
                {
                    WorksheetAccessor.FormulaReplaceSheetName(doc, "Source", "'Source 2'");
                }
                streamDoc.GetModifiedSmlDocument().SaveAs("../../FormulasUpdated.xlsx");
            }

            // Change sheet name in formulas
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(
                       SmlDocument.FromFileName("../../Formulas.xlsx")))
            {
                using (SpreadsheetDocument doc = streamDoc.GetSpreadsheetDocument())
                {
                    WorksheetPart sheet = WorksheetAccessor.GetWorksheet(doc, "References");
                    WorksheetAccessor.CopyCellRange(doc, sheet, 1, 1, 7, 5, 4, 8);
                }
                streamDoc.GetModifiedSmlDocument().SaveAs("../../FormulasCopied.xlsx");
            }
        }
 /// <summary>
 /// Validate the given <see cref="WmlDocument" />, using the <see cref="OpenXmlValidator" />.
 /// </summary>
 /// <param name="wmlDocument">The <see cref="WmlDocument" />.</param>
 protected static void Validate(WmlDocument wmlDocument)
 {
     using (var memoryStreamDocument = new OpenXmlMemoryStreamDocument(wmlDocument))
         using (WordprocessingDocument wordDocument = memoryStreamDocument.GetWordprocessingDocument())
         {
             Validate(wordDocument);
         }
 }
Esempio n. 11
0
 /// <summary>
 /// Convert to html
 /// </summary>
 /// <param name="doc"></param>
 /// <param name="htmlConverterSettings"></param>
 /// <returns></returns>
 public XElement ConvertToHtml(WmlDocument doc, HtmlConverterSettings htmlConverterSettings)
 {
     using (var streamDoc = new OpenXmlMemoryStreamDocument(doc))
     {
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
         {
             return(ConvertToHtml(document, htmlConverterSettings));
         }
     }
 }
Esempio n. 12
0
 /// <summary>
 /// Convert to html
 /// </summary>
 /// <param name="doc"></param>
 /// <param name="htmlConverterSettings"></param>
 /// <param name="imageHandler"></param>
 /// <returns></returns>
 public XElement ConvertToHtml(WmlDocument doc, HtmlConverterSettings htmlConverterSettings, Func <ImageInfo, XElement> imageHandler)
 {
     using (var streamDoc = new OpenXmlMemoryStreamDocument(doc))
     {
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
         {
             return(ConvertToHtml(document, htmlConverterSettings, imageHandler));
         }
     }
 }
Esempio n. 13
0
        public List <PersonFiles> SaveSplitDocument(Stream document)
        {
            List <PersonFiles> resultList = new List <PersonFiles>();

            byte[] byteArray = StreamTools.ReadFully(document);
            using (MemoryStream documentInMemoryStream = new MemoryStream(byteArray, 0, byteArray.Length, true, true))
            {
                foreach (OpenXMLDocumentPart <Sheet> element in DocumentElements)
                {
                    OpenXmlPowerToolsDocument docDividedPowerTools = new OpenXmlPowerToolsDocument(DocumentName, documentInMemoryStream);
                    using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(docDividedPowerTools))
                    {
                        SpreadsheetDocument excelDoc = streamDoc.GetSpreadsheetDocument();
                        excelDoc.WorkbookPart.Workbook.Sheets.RemoveAllChildren();
                        Sheets sheets = excelDoc.WorkbookPart.Workbook.Sheets;
                        foreach (Sheet compo in element.CompositeElements)
                        {
                            sheets.Append(compo.CloneNode(false));
                        }

                        excelDoc.WorkbookPart.Workbook.Save();

                        var person = new PersonFiles();
                        person.Person = element.PartOwner;
                        resultList.Add(person);
                        person.Name = element.Guid.ToString();
                        person.Data = streamDoc.GetModifiedDocument().DocumentByteArray;
                    }
                }

                OpenXmlPowerToolsDocument docPowerTools = new OpenXmlPowerToolsDocument(DocumentName, documentInMemoryStream);
                using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(docPowerTools))
                {
                    SpreadsheetDocument excelDoc = streamDoc.GetSpreadsheetDocument();

                    excelDoc.WorkbookPart.Workbook.Sheets.RemoveAllChildren();
                    excelDoc.WorkbookPart.Workbook.Save();

                    var person = new PersonFiles();
                    person.Person = "/";
                    resultList.Add(person);
                    person.Name = "template.xlsx";
                    person.Data = streamDoc.GetModifiedDocument().DocumentByteArray;
                }
            }

            var xmlPerson = new PersonFiles();

            xmlPerson.Person = "/";
            resultList.Add(xmlPerson);
            xmlPerson.Name = "mergeXmlDefinition.xml";
            xmlPerson.Data = CreateMergeXml();

            return(resultList);
        }
Esempio n. 14
0
 public static PmlDocument BuildPresentation(List <SlideSource> sources)
 {
     using var streamDoc = OpenXmlMemoryStreamDocument.CreatePresentationDocument();
     using (var output = streamDoc.GetPresentationDocument(new OpenSettings {
         AutoSave = false
     }))
     {
         BuildPresentation(sources, output);
     }
     return(streamDoc.GetModifiedPmlDocument());
 }
Esempio n. 15
0
        public List <PersonFiles> SaveSplitDocument(Stream document)
        {
            List <PersonFiles> resultList = new List <PersonFiles>();

            byte[] byteArray = StreamTools.ReadFully(document);
            using (MemoryStream documentInMemoryStream = new MemoryStream(byteArray, 0, byteArray.Length, true, true))
            {
                OpenXmlPowerToolsDocument docPowerTools = new OpenXmlPowerToolsDocument(DocumentName, documentInMemoryStream);
                using (OpenXmlMemoryStreamDocument streamTemplateDoc = new OpenXmlMemoryStreamDocument(docPowerTools))
                {
                    PresentationDocument templatePresentation = streamTemplateDoc.GetPresentationDocument();
                    foreach (OpenXMLDocumentPart <SlideId> element in DocumentElements)
                    {
                        OpenXmlPowerToolsDocument emptyDocPowerTools = new OpenXmlPowerToolsDocument(DocumentName, documentInMemoryStream);
                        using (OpenXmlMemoryStreamDocument streamDividedDoc = new OpenXmlMemoryStreamDocument(emptyDocPowerTools))
                        {
                            var relationshipIds = element.CompositeElements.Select(c => c.RelationshipId.Value).ToList();
                            PresentationDocument dividedPresentation = streamDividedDoc.GetPresentationDocument();
                            PresentationTools.InsertSlidesFromTemplate(PresentationTools.RemoveAllSlides(dividedPresentation), templatePresentation, relationshipIds);

                            var person = new PersonFiles();
                            person.Person = element.PartOwner;
                            resultList.Add(person);
                            person.Name = element.Guid.ToString();
                            person.Data = streamDividedDoc.GetModifiedDocument().DocumentByteArray;
                        }
                    }
                }

                using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(docPowerTools))
                {
                    PresentationDocument preDoc = streamDoc.GetPresentationDocument();
                    PresentationTools.RemoveAllSlides(preDoc);

                    var person = new PersonFiles();
                    person.Person = "/";
                    resultList.Add(person);
                    person.Name = "template.pptx";
                    person.Data = streamDoc.GetModifiedDocument().DocumentByteArray;
                }

                var xmlPerson = new PersonFiles();
                xmlPerson.Person = "/";
                resultList.Add(xmlPerson);
                xmlPerson.Name = "mergeXmlDefinition.xml";
                xmlPerson.Data = CreateMergeXml();
            }

            return(resultList);
        }
Esempio n. 16
0
        public void BuildExcelDocument(DataTable source, string targetFile, string tabName)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = OpenXmlMemoryStreamDocument.CreateSpreadsheetDocument())
            {
                using (SpreadsheetDocument doc = streamDoc.GetSpreadsheetDocument())
                {
                    WorksheetAccessor.CreateDefaultStyles(doc);
                    // We could use TableName as tabName:   source.TableName
                    WorksheetPart sheetPart = WorksheetAccessor.AddWorksheet(doc, tabName);

                    WriteDatasheet(doc, sheetPart, source, tabName);
                }
                //streamDoc.GetModifiedSmlDocument().SaveAs(targetFile);
                streamDoc.GetModifiedSmlDocument().SaveAs(targetFile);
            }
        }
Esempio n. 17
0
        public byte[] Run(List <PersonFiles> files)
        {
            var mergeXml = GetMergeXml(files);

            Body          body        = new Body();
            MergeDocument documentXml = mergeXml.Items.First();

            foreach (MergeDocumentPart part in documentXml.Part)
            {
                byte[] byteArray = files.Where(p => p.Person == part.Name && p.Name == part.Id).Select(d => d.Data).FirstOrDefault();
                using (MemoryStream docInMemoryStream = new MemoryStream(byteArray, 0, byteArray.Length, true, true))
                {
                    OpenXmlPowerToolsDocument docPowerTools = new OpenXmlPowerToolsDocument(string.Empty, docInMemoryStream);
                    using (OpenXmlMemoryStreamDocument streamEmptyDoc = new OpenXmlMemoryStreamDocument(docPowerTools))
                    {
                        WordprocessingDocument wordprocessingDocument = streamEmptyDoc.GetWordprocessingDocument();

                        // Assign a reference to the existing document body.
                        foreach (OpenXmlElement element in wordprocessingDocument.MainDocumentPart.Document.Body.ChildElements)
                        {
                            body.Append(element.CloneNode(true));
                        }

                        // Close the handle explicitly.
                        wordprocessingDocument.Close();
                    }
                }
            }

            byte[] template = files.Where(p => p.Person == "/" && p.Name == "template.docx").Select(d => d.Data).FirstOrDefault();
            using (MemoryStream docInMemoryStream = new MemoryStream(template, 0, template.Length, true, true))
            {
                OpenXmlPowerToolsDocument docPowerTools = new OpenXmlPowerToolsDocument(string.Empty, docInMemoryStream);
                using (OpenXmlMemoryStreamDocument streamEmptyDoc = new OpenXmlMemoryStreamDocument(docPowerTools))
                {
                    WordprocessingDocument wordDoc = streamEmptyDoc.GetWordprocessingDocument();
                    wordDoc.MainDocumentPart.Document.Body = body;
                    wordDoc.MainDocumentPart.Document.Save();

                    return(streamEmptyDoc.GetModifiedDocument().DocumentByteArray);
                }
            }
        }
 protected override void EndProcessing()
 {
     if (PassThru || !File.Exists(outputPath) || ShouldProcess(outputPath, "Export-OpenXmlWordprocessing"))
     {
         using (OpenXmlMemoryStreamDocument streamDoc = OpenXmlMemoryStreamDocument.CreateWordprocessingDocument())
         {
             using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
             {
                 if (processedObjects.Count > 0)
                 {
                     PowerToolsExtensions.SetContent(document, processedObjects.Select(e => new XElement(W.p, new XElement(W.r, new XElement(W.t, new XAttribute(XNamespace.Xml + "space", "preserve"), e)))));
                 }
             }
             OpenXmlPowerToolsDocument output = streamDoc.GetModifiedDocument();
             output.FileName = outputPath;
             OutputDocument(output);
         }
     }
 }
        public void SaveSplitDocumentShouldReturnValidTest2dDocuments()
        {
            var personFilesList = DocSampleSplit.SaveSplitDocument(PreSampleDocInMemory);
            var docs            = personFilesList.Where(p => p.Person == "test2").Select(u => u.Data);

            List <ValidationErrorInfo> validationErrors = new List <ValidationErrorInfo>();

            foreach (byte[] doc in docs)
            {
                MemoryStream partDocInMemory   = new MemoryStream(doc, 0, doc.Length, true, true);
                var          partDocPowerTools = new OpenXmlPowerToolsDocument("test2.pptx", partDocInMemory);

                OpenXmlMemoryStreamDocument partDocInMemoryExpandable = new OpenXmlMemoryStreamDocument(partDocPowerTools);

                validationErrors.AddRange(DocValidator.Validate(partDocInMemoryExpandable.GetPresentationDocument()));
            }

            Assert.IsTrue(docs.Count() > 0);
            Assert.AreEqual(0, validationErrors.Count());
        }
Esempio n. 20
0
        static void importFromOpenXML()
        {
            SmlDocument smldoc = new SmlDocument("C:\\Users\\fabio\\Desktop\\Book1.xlsx");

            var rng = SmlDataRetriever.RetrieveRange(smldoc, "Sheet1", 2, 2, 8, 8);



            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(
                       SmlDocument.FromFileName("C:\\Users\\fabio\\Desktop\\Book1.xlsx")))
            {
                using (SpreadsheetDocument doc = streamDoc.GetSpreadsheetDocument())
                {
                    int startRow;
                    int startCol;

                    findStartData(doc, out startCol, out startRow, 10, 10);
                }
                //streamDoc.GetModifiedSmlDocument().SaveAs(Path.Combine(tempDi.FullName, "FormulasUpdated.xlsx"));
            }
        }
Esempio n. 21
0
        public void PublishUsingPublishSlides(string sourcePath)
        {
            var targetDir = Path.Combine(TargetDirectory, Path.GetFileNameWithoutExtension(sourcePath));

            if (Directory.Exists(targetDir))
            {
                Directory.Delete(targetDir, true);
            }
            Directory.CreateDirectory(targetDir);

            var document = new PmlDocument(sourcePath);

            string   title;
            DateTime?modified;

            using (var streamDoc = new OpenXmlMemoryStreamDocument(document))
            {
                using var srcDoc = streamDoc.GetPresentationDocument(new OpenSettings { AutoSave = false });
                title            = srcDoc.PackageProperties.Title;
                modified         = srcDoc.PackageProperties.Modified;
            }

            var sameTitle = 0;

            foreach (var slide in PresentationBuilder.PublishSlides(document))
            {
                slide.SaveAs(Path.Combine(targetDir, Path.GetFileName(slide.FileName)));

                using var streamDoc = new OpenXmlMemoryStreamDocument(slide);
                using var slideDoc  = streamDoc.GetPresentationDocument(new OpenSettings { AutoSave = false });

                Assert.Equal(modified, slideDoc.PackageProperties.Modified);

                if (title.Equals(slideDoc.PackageProperties.Title))
                {
                    sameTitle++;
                }
            }
            Assert.InRange(sameTitle, 0, 4);
        }
 protected override void ProcessRecord()
 {
     foreach (var document in AllDocuments("Add-OpenXmlDocumentIndex"))
     {
         try
         {
             using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
             {
                 using (WordprocessingDocument doc = streamDoc.GetWordprocessingDocument())
                 {
                     IndexAccessor.Generate(doc);
                     StyleAccessor.CreateIndexStyles(doc, stylesSourcePath, addDefaultStyles);
                 }
                 OutputDocument(streamDoc.GetModifiedDocument());
             }
         }
         catch (Exception e)
         {
             WriteError(PowerToolsExceptionHandling.GetExceptionErrorRecord(e, document));
         }
     }
 }
 protected override void ProcessRecord()
 {
     foreach (var document in AllDocuments("Add-OpenXmlDocumentIndex"))
     {
         try
         {
             using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
             {
                 using (WordprocessingDocument doc = streamDoc.GetWordprocessingDocument())
                 {
                     IndexAccessor.Generate(doc);
                     StyleAccessor.CreateIndexStyles(doc, stylesSourcePath, addDefaultStyles);
                 }
                 OutputDocument(streamDoc.GetModifiedDocument());
             }
         }
         catch (Exception e)
         {
             WriteError(PowerToolsExceptionHandling.GetExceptionErrorRecord(e, document));
         }
     }
 }
Esempio n. 24
0
        public void PublishUsingPublishSlides(string sourcePath)
        {
            var targetDir = Path.Combine(TargetDirectory, Path.GetFileNameWithoutExtension(sourcePath));

            if (Directory.Exists(targetDir))
            {
                Directory.Delete(targetDir, true);
            }
            Directory.CreateDirectory(targetDir);

            using var srcStream = File.Open(sourcePath, FileMode.Open);
            var openSettings = new OpenSettings {
                AutoSave = false
            };

            using var srcDoc = OpenXmlExtensions.OpenPresentation(srcStream, false, openSettings);

            var title    = srcDoc.PackageProperties.Title ?? string.Empty;
            var modified = srcDoc.PackageProperties.Modified;

            var sameTitle = 0;

            foreach (var slide in PresentationBuilder.PublishSlides(srcDoc, sourcePath))
            {
                slide.SaveAs(Path.Combine(targetDir, Path.GetFileName(slide.FileName)));

                using var streamDoc = new OpenXmlMemoryStreamDocument(slide);
                using var slideDoc  = streamDoc.GetPresentationDocument(new OpenSettings { AutoSave = false });

                Assert.Equal(modified, slideDoc.PackageProperties.Modified);

                if (title.Equals(slideDoc.PackageProperties.Title))
                {
                    sameTitle++;
                }
            }
            Assert.InRange(sameTitle, 0, 4);
        }
Esempio n. 25
0
        public void Init()
        {
            PreTools     = new PresentationTools();
            DocValidator = new OpenXmlValidator();

            byte[] PreCGWBytes    = File.ReadAllBytes(@"../../../Files/6.CGW15-prezentacja.pptx");
            byte[] PreSampleBytes = File.ReadAllBytes(@"../../../Files/przykladowa-prezentacja.pptx");

            MemoryStream PreCGWDocInMemory    = new MemoryStream(PreCGWBytes, 0, PreCGWBytes.Length, true, true);
            MemoryStream PreSampleDocInMemory = new MemoryStream(PreSampleBytes, 0, PreSampleBytes.Length, true, true);

            OpenXmlPowerToolsDocument PreCGWDocPowerTools    = new OpenXmlPowerToolsDocument("6.CGW15 - prezentacja.pptx", PreCGWDocInMemory);
            OpenXmlPowerToolsDocument PreSampleDocPowerTools = new OpenXmlPowerToolsDocument("6.CGW15 - przykladowa-prezentacja.pptx", PreSampleDocInMemory);

            PreCGWDocInMemoryExpandable    = new OpenXmlMemoryStreamDocument(PreCGWDocPowerTools);
            PreSampleDocInMemoryExpandable = new OpenXmlMemoryStreamDocument(PreSampleDocPowerTools);

            PreCGWDoc    = PreCGWDocInMemoryExpandable.GetPresentationDocument();
            PreSampleDoc = PreSampleDocInMemoryExpandable.GetPresentationDocument();

            PreCGWDocInMemory.Close();
            PreSampleDocInMemory.Close();
        }
Esempio n. 26
0
        private static void BuildPresentation(List <SlideSource> sources, PresentationDocument output)
        {
            using var fluentBuilder = new FluentPresentationBuilder(output);

            var sourceNum    = 0;
            var openSettings = new OpenSettings {
                AutoSave = false
            };

            foreach (var source in sources)
            {
                using var streamDoc = new OpenXmlMemoryStreamDocument(source.PmlDocument);
                using var doc       = streamDoc.GetPresentationDocument(openSettings);
                try
                {
                    if (source.KeepMaster)
                    {
                        foreach (var slideMasterPart in doc.PresentationPart.SlideMasterParts)
                        {
                            fluentBuilder.AppendMaster(doc, slideMasterPart);
                        }
                    }
                    fluentBuilder.AppendSlides(doc, source.Start, source.Count);
                }
                catch (PresentationBuilderInternalException dbie)
                {
                    if (dbie.Message.Contains("{0}"))
                    {
                        throw new PresentationBuilderException(string.Format(dbie.Message, sourceNum));
                    }
                    throw;
                }

                sourceNum++;
            }
        }
Esempio n. 27
0
        static void Main(string[] args)
        {
            var n      = DateTime.Now;
            var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second));

            tempDi.Create();

            WmlDocument solarSystemDoc = new WmlDocument("../../solar-system.docx");

            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(solarSystemDoc))
                using (WordprocessingDocument solarSystem = streamDoc.GetWordprocessingDocument())
                {
                    // get children elements of the <w:body> element
                    var q1 = solarSystem
                             .MainDocumentPart
                             .GetXDocument()
                             .Root
                             .Element(W.body)
                             .Elements();

                    // project collection of tuples containing element and type
                    var q2 = q1
                             .Select(
                        e =>
                    {
                        string keyForGroupAdjacent = ".NonContentControl";
                        if (e.Name == W.sdt)
                        {
                            keyForGroupAdjacent = e.Element(W.sdtPr)
                                                  .Element(W.tag)
                                                  .Attribute(W.val)
                                                  .Value;
                        }
                        if (e.Name == W.sectPr)
                        {
                            keyForGroupAdjacent = null;
                        }
                        return(new
                        {
                            Element = e,
                            KeyForGroupAdjacent = keyForGroupAdjacent
                        });
                    }
                        ).Where(e => e.KeyForGroupAdjacent != null);

                    // group by type
                    var q3 = q2.GroupAdjacent(e => e.KeyForGroupAdjacent);

                    // temporary code to dump q3
                    foreach (var g in q3)
                    {
                        Console.WriteLine("{0}:  {1}", g.Key, g.Count());
                    }
                    //Environment.Exit(0);


                    // validate existence of files referenced in content controls
                    foreach (var f in q3.Where(g => g.Key != ".NonContentControl"))
                    {
                        string   filename = "../../" + f.Key + ".docx";
                        FileInfo fi       = new FileInfo(filename);
                        if (!fi.Exists)
                        {
                            Console.WriteLine("{0} doesn't exist.", filename);
                            Environment.Exit(0);
                        }
                    }

                    // project collection with opened WordProcessingDocument
                    var q4 = q3
                             .Select(g => new
                    {
                        Group    = g,
                        Document = g.Key != ".NonContentControl" ?
                                   new WmlDocument("../../" + g.Key + ".docx") :
                                   solarSystemDoc
                    });

                    // project collection of OpenXml.PowerTools.Source
                    var sources = q4
                                  .Select(
                        g =>
                    {
                        if (g.Group.Key == ".NonContentControl")
                        {
                            return(new Source(
                                       g.Document,
                                       g.Group
                                       .First()
                                       .Element
                                       .ElementsBeforeSelf()
                                       .Count(),
                                       g.Group
                                       .Count(),
                                       false));
                        }
                        else
                        {
                            return(new Source(g.Document, false));
                        }
                    }
                        ).ToList();

                    DocumentBuilder.BuildDocument(sources, Path.Combine(tempDi.FullName, "solar-system-new.docx"));
                }
        }
Esempio n. 28
0
        static void Main(string[] args)
        {
            // Update an existing pivot table
            FileInfo qs  = new FileInfo("../../QuarterlySales.xlsx");
            FileInfo qsu = new FileInfo("../../QuarterlyPivot.xlsx");

            int row = 1;

            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(
                       SmlDocument.FromFileName(qs.FullName)))
            {
                using (SpreadsheetDocument doc = streamDoc.GetSpreadsheetDocument())
                {
                    WorksheetPart sheet = WorksheetAccessor.GetWorksheet(doc, "Range");
                    using (StreamReader source = new StreamReader("../../PivotData.txt"))
                    {
                        while (!source.EndOfStream)
                        {
                            string line = source.ReadLine();
                            if (line.Length > 3)
                            {
                                string[] fields = line.Split(',');
                                int      column = 1;
                                foreach (string item in fields)
                                {
                                    double num;
                                    if (double.TryParse(item, out num))
                                    {
                                        WorksheetAccessor.SetCellValue(doc, sheet, row, column++, num);
                                    }
                                    else
                                    {
                                        WorksheetAccessor.SetCellValue(doc, sheet, row, column++, item);
                                    }
                                }
                            }
                            row++;
                        }
                    }
                    sheet.PutXDocument();

                    WorksheetAccessor.UpdateRangeEndRow(doc, "Sales", row - 1);
                }
                streamDoc.GetModifiedSmlDocument().SaveAs(qsu.FullName);
            }

            // Create from scratch
            row = 1;
            int maxColumn = 1;

            using (OpenXmlMemoryStreamDocument streamDoc = OpenXmlMemoryStreamDocument.CreateSpreadsheetDocument())
            {
                using (SpreadsheetDocument doc = streamDoc.GetSpreadsheetDocument())
                {
                    WorksheetAccessor.CreateDefaultStyles(doc);
                    WorksheetPart     sheet = WorksheetAccessor.AddWorksheet(doc, "Range");
                    MemorySpreadsheet ms    = new MemorySpreadsheet();

#if false
                    int font0 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 1),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font2 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Bold   = true,
                        Size   = 18,
                        Color  = new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 3),
                        Name   = "Cambria",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Major
                    });
                    int font3 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Bold   = true,
                        Size   = 15,
                        Color  = new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 3),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font4 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Bold   = true,
                        Size   = 13,
                        Color  = new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 3),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font5 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Bold   = true,
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 3),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font6 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo("FF006100"),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font7 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo("FF9C0006"),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font8 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo("FF9C6500"),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font9 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo("FF3F3F76"),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font10 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Bold   = true,
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo("FF3F3F3F"),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font11 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Bold   = true,
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo("FFFA7D00"),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font12 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo("FFFA7D00"),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font13 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Bold   = true,
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 0),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font14 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo("FFFF0000"),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font15 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Italic = true,
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo("FF7F7F7F"),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font16 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Bold   = true,
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 1),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });
                    int font17 = WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Size   = 11,
                        Color  = new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 0),
                        Name   = "Calibri",
                        Family = 2,
                        Scheme = WorksheetAccessor.Font.SchemeType.Minor
                    });

                    int fill0 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.None, null, null));
                    int fill1 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Gray125, null, null));
                    int fill2 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                      null, new WorksheetAccessor.ColorInfo("FFC6EFCE")));
                    int fill3 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                      null, new WorksheetAccessor.ColorInfo("FFFFC7CE")));
                    int fill4 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                      null, new WorksheetAccessor.ColorInfo("FFFFEB9C")));
                    int fill5 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                      null, new WorksheetAccessor.ColorInfo("FFFFCC99")));
                    int fill6 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                      null, new WorksheetAccessor.ColorInfo("FFF2F2F2")));
                    int fill7 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                      null, new WorksheetAccessor.ColorInfo("FFA5A5A5")));
                    int fill8 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                      null, new WorksheetAccessor.ColorInfo("FFFFFFCC")));
                    int fill9 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                      null, new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 4)));
                    int fill10 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(4, 0.79998168889431442)));
                    int fill11 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(4, 0.59999389629810485)));
                    int fill12 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(4, 0.39997558519241921)));
                    int fill13 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       null, new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 5)));
                    int fill14 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(5, 0.79998168889431442)));
                    int fill15 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(5, 0.59999389629810485)));
                    int fill16 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(5, 0.39997558519241921)));
                    int fill17 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       null, new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 6)));
                    int fill18 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(6, 0.79998168889431442)));
                    int fill19 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(6, 0.59999389629810485)));
                    int fill20 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(6, 0.39997558519241921)));
                    int fill21 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       null, new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 7)));
                    int fill22 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(7, 0.79998168889431442)));
                    int fill23 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(7, 0.59999389629810485)));
                    int fill24 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(7, 0.39997558519241921)));
                    int fill25 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       null, new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 8)));
                    int fill26 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(8, 0.79998168889431442)));
                    int fill27 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(8, 0.59999389629810485)));
                    int fill28 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(8, 0.39997558519241921)));
                    int fill29 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       null, new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 9)));
                    int fill30 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(9, 0.79998168889431442)));
                    int fill31 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(9, 0.59999389629810485)));
                    int fill32 = WorksheetAccessor.GetFillIndex(doc, new WorksheetAccessor.PatternFill(WorksheetAccessor.PatternFill.PatternType.Solid,
                                                                                                       new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Indexed, 65),
                                                                                                       new WorksheetAccessor.ColorInfo(9, 0.39997558519241921)));

                    int border1 = WorksheetAccessor.GetBorderIndex(doc, new WorksheetAccessor.Border
                    {
                        Bottom = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thick,
                                                                  new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 4))
                    });
                    int border2 = WorksheetAccessor.GetBorderIndex(doc, new WorksheetAccessor.Border
                    {
                        Bottom = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thick, new WorksheetAccessor.ColorInfo(4, 0.499984740745262))
                    });
                    int border3 = WorksheetAccessor.GetBorderIndex(doc, new WorksheetAccessor.Border
                    {
                        Bottom = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Medium, new WorksheetAccessor.ColorInfo(4, 0.39997558519241921))
                    });
                    int border4 = WorksheetAccessor.GetBorderIndex(doc, new WorksheetAccessor.Border
                    {
                        Left   = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin, new WorksheetAccessor.ColorInfo("FF7F7F7F")),
                        Right  = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin, new WorksheetAccessor.ColorInfo("FF7F7F7F")),
                        Top    = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin, new WorksheetAccessor.ColorInfo("FF7F7F7F")),
                        Bottom = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin, new WorksheetAccessor.ColorInfo("FF7F7F7F"))
                    });
                    int border5 = WorksheetAccessor.GetBorderIndex(doc, new WorksheetAccessor.Border
                    {
                        Left   = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin, new WorksheetAccessor.ColorInfo("FF3F3F3F")),
                        Right  = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin, new WorksheetAccessor.ColorInfo("FF3F3F3F")),
                        Top    = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin, new WorksheetAccessor.ColorInfo("FF3F3F3F")),
                        Bottom = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin, new WorksheetAccessor.ColorInfo("FF3F3F3F"))
                    });
                    int border6 = WorksheetAccessor.GetBorderIndex(doc, new WorksheetAccessor.Border
                    {
                        Bottom = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Double, new WorksheetAccessor.ColorInfo("FFFF8001"))
                    });
                    int border7 = WorksheetAccessor.GetBorderIndex(doc, new WorksheetAccessor.Border
                    {
                        Left   = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Double, new WorksheetAccessor.ColorInfo("FF3F3F3F")),
                        Right  = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Double, new WorksheetAccessor.ColorInfo("FF3F3F3F")),
                        Top    = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Double, new WorksheetAccessor.ColorInfo("FF3F3F3F")),
                        Bottom = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Double, new WorksheetAccessor.ColorInfo("FF3F3F3F"))
                    });
                    int border8 = WorksheetAccessor.GetBorderIndex(doc, new WorksheetAccessor.Border
                    {
                        Left   = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin, new WorksheetAccessor.ColorInfo("FFB2B2B2")),
                        Right  = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin, new WorksheetAccessor.ColorInfo("FFB2B2B2")),
                        Top    = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin, new WorksheetAccessor.ColorInfo("FFB2B2B2")),
                        Bottom = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin, new WorksheetAccessor.ColorInfo("FFB2B2B2"))
                    });
                    int border9 = WorksheetAccessor.GetBorderIndex(doc, new WorksheetAccessor.Border
                    {
                        Top = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin,
                                                               new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 4)),
                        Bottom = new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Double,
                                                                  new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 4))
                    });
#endif

                    int southIndex = WorksheetAccessor.GetStyleIndex(doc, 0, 8, 1, 2,
                                                                     new WorksheetAccessor.CellAlignment {
                        HorizontalAlignment = WorksheetAccessor.CellAlignment.Horizontal.Center
                    },
                                                                     true, false);
                    WorksheetAccessor.GradientFill gradient = new WorksheetAccessor.GradientFill(90);
                    gradient.AddStop(new WorksheetAccessor.GradientStop(0, new WorksheetAccessor.ColorInfo("FF92D050")));
                    gradient.AddStop(new WorksheetAccessor.GradientStop(1, new WorksheetAccessor.ColorInfo("FF0070C0")));
                    int northIndex = WorksheetAccessor.GetStyleIndex(doc, 0,
                                                                     WorksheetAccessor.GetFontIndex(doc, new WorksheetAccessor.Font
                    {
                        Italic = true,
                        Size   = 8,
                        Color  = new WorksheetAccessor.ColorInfo(WorksheetAccessor.ColorInfo.ColorType.Theme, 1),
                        Name   = "Times New Roman",
                        Family = 1
                    }),
                                                                     WorksheetAccessor.GetFillIndex(doc, gradient),
                                                                     WorksheetAccessor.GetBorderIndex(doc, new WorksheetAccessor.Border
                    {
                        DiagonalDown = true,
                        Diagonal     =
                            new WorksheetAccessor.BorderLine(WorksheetAccessor.BorderLine.LineStyle.Thin, new WorksheetAccessor.ColorInfo("FF616100"))
                    }),
                                                                     null, false, false);
                    WorksheetAccessor.CheckNumberFormat(doc, 100, "_(\"$\"* #,##0.00_);_(\"$\"* \\(#,##0.00\\);_(\"$\"* \"-\"??_);_(@_)");
                    int amountIndex = WorksheetAccessor.GetStyleIndex(doc, 100, 0, 0, 0, null, false, false);

                    using (StreamReader source = new StreamReader("../../PivotData.txt"))
                    {
                        while (!source.EndOfStream)
                        {
                            string line = source.ReadLine();
                            if (line.Length > 3)
                            {
                                string[] fields = line.Split(',');
                                int      column = 1;
                                foreach (string item in fields)
                                {
                                    double num;
                                    if (double.TryParse(item, out num))
                                    {
                                        if (column == 6)
                                        {
                                            ms.SetCellValue(row, column++, num, amountIndex);
                                        }
                                        else
                                        {
                                            ms.SetCellValue(row, column++, num);
                                        }
                                    }
                                    else if (item == "Accessories")
                                    {
                                        ms.SetCellValue(row, column++, item, WorksheetAccessor.GetStyleIndex(doc, "Good"));
                                    }
                                    else if (item == "South")
                                    {
                                        ms.SetCellValue(row, column++, item, southIndex);
                                    }
                                    else if (item == "North")
                                    {
                                        ms.SetCellValue(row, column++, item, northIndex);
                                    }
                                    else
                                    {
                                        ms.SetCellValue(row, column++, item);
                                    }
                                }
                                maxColumn = column - 1;
                            }
                            row++;
                        }
                    }
                    WorksheetAccessor.SetSheetContents(doc, sheet, ms);
                    WorksheetAccessor.SetRange(doc, "Sales", "Range", 1, 1, row - 1, maxColumn);
                    WorksheetPart pivot = WorksheetAccessor.AddWorksheet(doc, "Pivot");
                    WorksheetAccessor.CreatePivotTable(doc, "Sales", pivot);

                    // Configure pivot table rows, columns, data and filters
                    WorksheetAccessor.AddPivotAxis(doc, pivot, "Year", WorksheetAccessor.PivotAxis.Column);
                    WorksheetAccessor.AddPivotAxis(doc, pivot, "Quarter", WorksheetAccessor.PivotAxis.Column);
                    WorksheetAccessor.AddPivotAxis(doc, pivot, "Category", WorksheetAccessor.PivotAxis.Row);
                    WorksheetAccessor.AddPivotAxis(doc, pivot, "Product", WorksheetAccessor.PivotAxis.Row);
                    WorksheetAccessor.AddDataValue(doc, pivot, "Amount");
                    WorksheetAccessor.AddPivotAxis(doc, pivot, "Region", WorksheetAccessor.PivotAxis.Page);
                }
                streamDoc.GetModifiedSmlDocument().SaveAs("../../NewPivot.xlsx");
            }


            // Add pivot table to existing spreadsheet
            // Demonstrate multiple data fields
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(
                       SmlDocument.FromFileName("../../QuarterlyUnitSales.xlsx")))
            {
                using (SpreadsheetDocument doc = streamDoc.GetSpreadsheetDocument())
                {
                    WorksheetPart pivot = WorksheetAccessor.AddWorksheet(doc, "Pivot");
                    WorksheetAccessor.CreatePivotTable(doc, "Sales", pivot);

                    // Configure pivot table rows, columns, data and filters
                    WorksheetAccessor.AddPivotAxis(doc, pivot, "Year", WorksheetAccessor.PivotAxis.Column);
                    WorksheetAccessor.AddPivotAxis(doc, pivot, "Quarter", WorksheetAccessor.PivotAxis.Column);
                    WorksheetAccessor.AddPivotAxis(doc, pivot, "Category", WorksheetAccessor.PivotAxis.Row);
                    WorksheetAccessor.AddPivotAxis(doc, pivot, "Product", WorksheetAccessor.PivotAxis.Row);
                    WorksheetAccessor.AddDataValue(doc, pivot, "Total");
                    WorksheetAccessor.AddDataValue(doc, pivot, "Quantity");
                    WorksheetAccessor.AddDataValue(doc, pivot, "Unit Price");
                    WorksheetAccessor.AddPivotAxis(doc, pivot, "Region", WorksheetAccessor.PivotAxis.Page);
                }
                streamDoc.GetModifiedSmlDocument().SaveAs("../../QuarterlyUnitSalesWithPivot.xlsx");
            }
        }
Esempio n. 29
0
        public List <PersonFiles> SaveSplitDocument(Stream document)
        {
            List <PersonFiles> resultList = new List <PersonFiles>();

            byte[] byteArray = StreamTools.ReadFully(document);
            using (MemoryStream documentInMemoryStream = new MemoryStream(byteArray, 0, byteArray.Length, true, true))
            {
                foreach (OpenXMLDocumentPart <OpenXmlElement> element in DocumentElements)
                {
                    OpenXmlPowerToolsDocument docDividedPowerTools = new OpenXmlPowerToolsDocument(DocumentName, documentInMemoryStream);
                    using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(docDividedPowerTools))
                    {
                        WordprocessingDocument wordDoc = streamDoc.GetWordprocessingDocument();
                        wordDoc.MainDocumentPart.Document.Body.RemoveAllChildren();
                        Body body = wordDoc.MainDocumentPart.Document.Body;
                        foreach (OpenXmlElement compo in element.CompositeElements)
                        {
                            body.Append(compo.CloneNode(true));
                        }

                        wordDoc.MainDocumentPart.Document.Save();

                        var person = new PersonFiles();
                        person.Person = element.PartOwner;
                        resultList.Add(person);
                        person.Name = element.Guid.ToString();
                        person.Data = streamDoc.GetModifiedDocument().DocumentByteArray;
                    }
                }
                // At this point, the memory stream contains the modified document.
                // We could write it back to a SharePoint document library or serve
                // it from a web server.

                OpenXmlPowerToolsDocument docPowerTools = new OpenXmlPowerToolsDocument(DocumentName, documentInMemoryStream);
                using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(docPowerTools))
                {
                    WordprocessingDocument wordDoc = streamDoc.GetWordprocessingDocument();

                    wordDoc.MainDocumentPart.Document.Body.RemoveAllChildren();
                    wordDoc.MainDocumentPart.Document.Save();

                    var person = new PersonFiles();
                    person.Person = "/";
                    resultList.Add(person);
                    person.Name = "template.docx";
                    person.Data = streamDoc.GetModifiedDocument().DocumentByteArray;
                }
            }
            // At this point, the memory stream contains the modified document.
            // We could write it back to a SharePoint document library or serve
            // it from a web server.

            var xmlPerson = new PersonFiles();

            xmlPerson.Person = "/";
            resultList.Add(xmlPerson);
            xmlPerson.Name = "mergeXmlDefinition.xml";
            xmlPerson.Data = CreateMergeXml();

            return(resultList);
        }
Esempio n. 30
0
 public static IList <PmlDocument> PublishSlides(PmlDocument src)
 {
     using var streamSrcDoc = new OpenXmlMemoryStreamDocument(src);
     using var srcDoc       = streamSrcDoc.GetPresentationDocument(new OpenSettings { AutoSave = false });
     return(PublishSlides(srcDoc, src.FileName).ToList());
 }
        static void Main(string[] args)
        {
            var n      = DateTime.Now;
            var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second));

            tempDi.Create();

            string presentation       = "../../Presentation1.pptx";
            string hiddenPresentation = "../../HiddenPresentation.pptx";

            // First, load both presentations into byte arrays, simulating retrieving presentations from some source
            // such as a SharePoint server
            var baPresentation       = File.ReadAllBytes(presentation);
            var baHiddenPresentation = File.ReadAllBytes(hiddenPresentation);

            // Next, replace "thee" with "the" in the main presentation
            var         pmlMainPresentation      = new PmlDocument("Main.pptx", baPresentation);
            PmlDocument modifiedMainPresentation = null;

            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(pmlMainPresentation))
            {
                using (PresentationDocument document = streamDoc.GetPresentationDocument())
                {
                    var pXDoc = document.PresentationPart.GetXDocument();
                    foreach (var slideId in pXDoc.Root.Elements(P.sldIdLst).Elements(P.sldId))
                    {
                        var slideRelId = (string)slideId.Attribute(R.id);
                        var slidePart  = document.PresentationPart.GetPartById(slideRelId);
                        var slideXDoc  = slidePart.GetXDocument();
                        var paragraphs = slideXDoc.Descendants(A.p).ToList();
                        OpenXmlRegex.Replace(paragraphs, new Regex("thee"), "the", null);
                        slidePart.PutXDocument();
                    }
                }
                modifiedMainPresentation = streamDoc.GetModifiedPmlDocument();
            }

            // Combine the two presentations into a single presentation
            var slideSources = new List <SlideSource>()
            {
                new SlideSource(modifiedMainPresentation, 0, 1, true),
                new SlideSource(new PmlDocument("Hidden.pptx", baHiddenPresentation), true),
                new SlideSource(modifiedMainPresentation, 1, true),
            };
            PmlDocument combinedPresentation = PresentationBuilder.BuildPresentation(slideSources);

            // Replace <# TRADEMARK #> with AdventureWorks (c)
            PmlDocument modifiedCombinedPresentation = null;

            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(combinedPresentation))
            {
                using (PresentationDocument document = streamDoc.GetPresentationDocument())
                {
                    var pXDoc = document.PresentationPart.GetXDocument();
                    foreach (var slideId in pXDoc.Root.Elements(P.sldIdLst).Elements(P.sldId).Skip(1).Take(1))
                    {
                        var slideRelId = (string)slideId.Attribute(R.id);
                        var slidePart  = document.PresentationPart.GetPartById(slideRelId);
                        var slideXDoc  = slidePart.GetXDocument();
                        var paragraphs = slideXDoc.Descendants(A.p).ToList();
                        OpenXmlRegex.Replace(paragraphs, new Regex("<# TRADEMARK #>"), "AdventureWorks (c)", null);
                        slidePart.PutXDocument();
                    }
                }
                modifiedCombinedPresentation = streamDoc.GetModifiedPmlDocument();
            }

            // we now have a PmlDocument (which is essentially a byte array) that can be saved as necessary.
            modifiedCombinedPresentation.SaveAs(Path.Combine(tempDi.FullName, "Modified.pptx"));
        }