Example #1
1
        public ExcelHelper Open(string ExcelFile,bool IsEditable=false)
        {
            _expectSheets = new List<string>();
            OpenSettings os = new OpenSettings();
            this._excelFilePath = ExcelFile;
            _doc = SpreadsheetDocument.Open(_excelFilePath, IsEditable);
            _wbPart = _doc.WorkbookPart;
            _shareStringPart = _wbPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();

            shareStringDic = new Dictionary<int, string>();

            int j = 0;

            foreach (var item in _shareStringPart.SharedStringTable.Elements<SharedStringItem>()) {
                shareStringDic.Add(j, item.InnerText);
                j++;
            }

            return _instance;
        }
 /// <summary>
 /// Create an OpenXML SDK PresentationDocument object
 /// from a docx4j PresentationMLPackage
 /// </summary>
 /// <param name="pptxPkg"></param>
 /// <param name="isEditable"></param>
 /// <param name="openSettings"></param>
 /// <returns></returns>
 public static PresentationDocument createPresentationDocument(
     PresentationMLPackage pptxPkg, 
     bool isEditable, OpenSettings openSettings)
 {
     return PresentationDocument.Open(
         new MemoryStream(SaveFromJavaUtils.toBytes(pptxPkg)), 
         isEditable, openSettings);
 }
 /// <summary>
 /// Create an OpenXML SDK SpreadsheetDocument object from a
 /// docx4j SpreadsheetMLPackage
 /// </summary>
 /// <param name="xlsxPkg"></param>
 /// <param name="isEditable"></param>
 /// <param name="openSettings"></param>
 /// <returns></returns>
 public static SpreadsheetDocument createPresentationDocument(
     SpreadsheetMLPackage xlsxPkg, 
     bool isEditable, OpenSettings openSettings)
 {
     return SpreadsheetDocument.Open(
         new MemoryStream(SaveFromJavaUtils.toBytes(xlsxPkg)), 
         isEditable, openSettings);
 }
 /// <summary>
 /// Create an OpenXML SDK WordprocessingDocument object
 /// from a docx4j WordprocessingMLPackage
 /// </summary>
 /// <param name="wordPkg"></param>
 /// <param name="isEditable"></param>
 /// <param name="openSettings"></param>
 /// <returns></returns>
 public static WordprocessingDocument createWordprocessingDocument(
     WordprocessingMLPackage wordPkg, 
     bool isEditable, OpenSettings openSettings)
 {
     return WordprocessingDocument.Open(
         new MemoryStream(SaveFromJavaUtils.toBytes(wordPkg)), 
         isEditable, openSettings);
 }
Example #5
0
 public void X007_SpreadsheetDocument_Open()
 {
     var fiSource = new FileInfo(Path.Combine(s_TestFileLocation, "Spreadsheet.xlsx"));
     var fiCopy = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, Guid.NewGuid().ToString() + ".xlsx"));
     File.Copy(fiSource.FullName, fiCopy.FullName);
     OpenSettings openSettings = new OpenSettings();
     openSettings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2013);
     using (SpreadsheetDocument doc = SpreadsheetDocument.Open(fiCopy.FullName, true, openSettings))
     {
         OpenXmlValidator v = new OpenXmlValidator(FileFormatVersions.Office2013);
         var errs = v.Validate(doc);
         Assert.Equal(1, errs.Count());
     }
     if (TestUtil.DeleteTempFiles)
         fiCopy.Delete();
 }
Example #6
0
 public void P005_PptxCreation_Package_Settings()
 {
     var fiSource = new FileInfo(Path.Combine(s_TestFileLocation, "Presentation.pptx"));
     var fiCopy = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, Guid.NewGuid().ToString() + ".pptx"));
     File.Copy(fiSource.FullName, fiCopy.FullName);
     using (Package package = Package.Open(fiCopy.FullName, FileMode.Open, FileAccess.ReadWrite))
     {
         OpenSettings openSettings = new OpenSettings();
         openSettings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2013);
         using (PresentationDocument doc = PresentationDocument.Open(package, openSettings))
         {
             OpenXmlValidator v = new OpenXmlValidator(FileFormatVersions.Office2013);
             var errs = v.Validate(doc);
             Assert.Equal(94, errs.Count());
         }
     }
     if (TestUtil.DeleteTempFiles)
         fiCopy.Delete();
 }
Example #7
0
        private void CreateChartSlides(TaskGroupData taskData, int lowestSLideIndex, ref int createdCount, PresentationPart oPPart)
        {
            Repository.Utility.WriteLog("CreateChartSlides started", System.Diagnostics.EventLogEntryType.Information);
            try
            {
                if (ChartSlidePart == null)
                    return;
                if (taskData.ChartsData == null || taskData.ChartsData.Keys.Count == 0 || !taskData.ChartsData.Keys.Any(t=>t.StartsWith("Show On")))
                {
                    createdCount++;
                    return;
                }

                if (taskData.ChartsData != null)
                {
                    foreach (string key in taskData.ChartsData.Keys)
                    {
                        try
                        {
                            if (key.StartsWith("Show On"))
                            {
                                //Get all Tasks related to  Driving path
                                TaskItemGroup newGroup = new TaskItemGroup() { ChartTaskItems = taskData.ChartsData[key] };
                                var chartDataTable = newGroup.GetChartDataTable(key);

                                #region Charts
                                if (chartDataTable != null)
                                {

                                    SlidePart chartSlidePart = oPPart.GetSlidePartsInOrder().ToList()[lowestSLideIndex + createdCount];

                                    if (chartSlidePart.ChartParts.ToList().Count > 0)
                                    {
                                        createdCount++;
                                        var chartPart = chartSlidePart.ChartParts.ToList()[0];

                                        foreach (IdPartPair part in chartPart.Parts)
                                        {
                                            var spreadsheet = chartPart.GetPartById(part.RelationshipId) as EmbeddedPackagePart;

                                            if (spreadsheet != null)
                                            {
                                                OpenSettings settings  = new OpenSettings();
                                                settings.AutoSave = true;
                                                using (var oSDoc = SpreadsheetDocument.Open(spreadsheet.GetStream(FileMode.OpenOrCreate, FileAccess.ReadWrite), true,settings))
                                                {
                                                    var workSheetPart = oSDoc.WorkbookPart.GetPartsOfType<WorksheetPart>().FirstOrDefault();
                                                    var sheetData = workSheetPart.Worksheet.Elements<SheetData>().FirstOrDefault();
                                                    for (int i = sheetData.Elements().Count() - 1; i >= 2; i--)
                                                    {
                                                        sheetData.ElementAt(i).Remove();
                                                    }
                                                    string reference = workSheetPart.TableDefinitionParts.ElementAt(0).Table.Reference.Value;
                                                    string length = reference.Split(":".ToCharArray())[1].Replace("I","");
                                                    WorkbookUtilities.ReplicateRow(sheetData, 2, chartDataTable.Rows.Count - 1);
                                                    WorkbookUtilities.LoadSheetData(sheetData, chartDataTable, 1, 0);
                                                    workSheetPart.TableDefinitionParts.ElementAt(0).Table.Reference.Value = reference.Replace(length, (chartDataTable.Rows.Count + 1).ToString());
                                                    BarChartUtilities.LoadChartData(chartPart, chartDataTable);
                                                    workSheetPart.TableDefinitionParts.ElementAt(0).Table.Save();
                                                    workSheetPart.Worksheet.Save();

                                                }

                                                break;
                                            }
                                        }

                                        var titleShape = chartSlidePart.Slide.Descendants<DocumentFormat.OpenXml.Presentation.Shape>().ToList();
                                        if (titleShape.Count > 0)
                                        {
                                            titleShape[0].TextBody = new DocumentFormat.OpenXml.Presentation.TextBody(
                                                                  new DocumentFormat.OpenXml.Drawing.BodyProperties(),
                                                                  new DocumentFormat.OpenXml.Drawing.ListStyle(),
                                                                  new DocumentFormat.OpenXml.Drawing.Paragraph(
                                                                  new DocumentFormat.OpenXml.Drawing.Run(
                                                                  new DocumentFormat.OpenXml.Drawing.RunProperties() { FontSize = 3600 },
                                                                  new DocumentFormat.OpenXml.Drawing.Text { Text = key.Replace("Show On_", "") })));
                                        }

                                    }
                                #endregion
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Repository.Utility.WriteLog(string.Format("CreateChartSlides had an error and the error message={0}", ex.Message), System.Diagnostics.EventLogEntryType.Information);
                            continue;
                        }

                    }

                }
            }
            catch (Exception ex)
            {
                Repository.Utility.WriteLog(string.Format("CreateChartSlides had an error and the error message={0}", ex.Message), System.Diagnostics.EventLogEntryType.Information);
            }

            Repository.Utility.WriteLog("CreateChartSlides completed", System.Diagnostics.EventLogEntryType.Information);
        }
        public static void CreateAddDataSpreadsheetWorkBook(string filepath)
        {
            OpenSettings openSettings = new OpenSettings();

            openSettings.MarkupCompatibilityProcessSettings =
                new MarkupCompatibilityProcessSettings(
                    MarkupCompatibilityProcessMode.ProcessAllParts,
                    FileFormatVersions.Office2013
                    );

            SpreadsheetDocument spreadsheet = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);

            WorkbookPart workbookPart = spreadsheet.AddWorkbookPart();

            workbookPart.Workbook = new Workbook();

            WorksheetPart worksheetPart = workbookPart.AddNewPart <WorksheetPart>();

            worksheetPart.Worksheet = new Worksheet(new SheetData());

            Sheets sheets = spreadsheet.WorkbookPart.Workbook.AppendChild <Sheets>(new Sheets());
            Sheet  sheet  = new Sheet()
            {
                Id = spreadsheet.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet"
            };

            sheets.Append(sheet);

            //  Adding data:
            SheetData sheetData = worksheetPart.Worksheet.GetFirstChild <SheetData>();
            //  Add a row:
            Row row;

            row = new Row()
            {
                RowIndex = 1
            };
            sheetData.Append(row);

            //  Find the A1 cell in the first Cell
            Cell refCell = null;

            foreach (Cell cell in row.Elements <Cell>())
            {
                if (string.Compare(cell.CellReference.Value, "A1", true) > 0)
                {
                    refCell = cell;
                    break;
                }
            }
            Cell newCell = new Cell()
            {
                CellReference = "A1"
            };

            row.InsertBefore(newCell, refCell);

            //  Set the cell value:
            newCell.CellValue = new CellValue("100");
            //Can be Shared String here:
            newCell.DataType = new EnumValue <CellValues>(CellValues.Number);

            workbookPart.Workbook.Save();
            spreadsheet.Close();
        }
Example #9
0
        /// <summary>
        /// 加载Excel数据
        /// </summary>
        /// <param name="path"></param>
        /// <param name="firstHeader">首行为标题,默认true</param>
        /// <returns></returns>
        public DataSet FromFile(string path, bool firstHeader = true)
        {
            DataSet dsResult = new DataSet();

            try
            {
                if (!File.Exists(path))
                {
                    Log.ShowError("当前文档正在被编辑,请关闭后操作!");
                    return(dsResult);
                }

                FileInfo fileInfo = new FileInfo(path);
                if (fileInfo.IsReadOnly)
                {
                    Log.ShowError("当前文档正在被编辑,请关闭后操作!");
                    return(dsResult);
                }

                //OpenSettings:Excel打开后的设置
                OpenSettings openSettings = new OpenSettings
                {
                    //设置Excel不自动保存
                    AutoSave = false
                };
                SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(path, true, openSettings);
                m_WorkbookPart = spreadsheetDocument.WorkbookPart;
                Sheets sheets = m_WorkbookPart.Workbook.Sheets;
                foreach (Sheet sheet in sheets)
                {
                    DataTable dt = new DataTable();
                    dt.TableName = sheet.Name;
                    WorksheetPart sheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id);

                    int rowIndex = 0;
                    foreach (Row row in sheetPart.Worksheet.Descendants <Row>())
                    {
                        DataRow dtRow    = null;
                        int     colIndex = 0;
                        foreach (Cell cell in row.Descendants <Cell>())
                        {
                            if (firstHeader && rowIndex == 0)
                            {
                                dt.Columns.Add(GetCellValue(spreadsheetDocument, cell));
                            }
                            else if (dtRow == null)
                            {
                                dtRow = dt.NewRow();
                                dt.Rows.Add(dtRow);
                                dtRow[colIndex] = GetCellValue(spreadsheetDocument, cell);
                            }
                            else
                            {
                                dtRow[colIndex] = GetCellValue(spreadsheetDocument, cell);
                            }

                            colIndex++;
                        }

                        rowIndex++;
                    }

                    dsResult.Tables.Add(dt);
                }
                spreadsheetDocument.Close();
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }

            return(dsResult);
        }
        public static ExcelDocument Open(string path, bool isEditable, OpenSettings openSettings)
        {
            SpreadsheetDocument doc = SpreadsheetDocument.Open(path, isEditable, openSettings);

            return(new ExcelDocument(doc));
        }
        public void AutoSaveOpenTest()
        {
            #region WordprocesingDocument.Open test
            string testDocxFile = "autosave.docx";
            PrepareTestFile(testDocxFile, TestFileStreams.complex0docx);
            OpenSettings s = new OpenSettings();
            s.AutoSave = false;
            using (var doc = WordprocessingDocument.Open(testDocxFile, true, s))
            {
                // do something, and changes should not be saved.
                var firstText = doc.MainDocumentPart.Document.Descendants<Text>().First();
                firstText.Text = "Changed";
            }

            s.AutoSave = true;
            using (var doc = WordprocessingDocument.Open(testDocxFile, true, s))
            {
                // check first.
                var firstText = doc.MainDocumentPart.Document.Descendants<Text>().First();
                Assert.NotEqual("Changed", firstText.Text);
                // do changes, and changes shoud be saved.
                firstText.Text = "Changed";
            }
            using (var docxStream = new FileStream(testDocxFile, FileMode.Open, FileAccess.ReadWrite))
            using (var doc = WordprocessingDocument.Open(docxStream, true))
            {
                var firstText = doc.MainDocumentPart.Document.Descendants<Text>().First();
                Assert.Equal("Changed", firstText.Text);

                firstText.Text = "Changed2";
            }
            using (var docxPackage = System.IO.Packaging.Package.Open(testDocxFile))
            using (var doc = WordprocessingDocument.Open(docxPackage, s))
            {
                var firstText = doc.MainDocumentPart.Document.Descendants<Text>().First();
                Assert.Equal("Changed2", firstText.Text);

                firstText.Text = "Changed3";
            }
            using (var doc = WordprocessingDocument.Open(testDocxFile, false))
            {
                // check
                var firstText = doc.MainDocumentPart.Document.Descendants<Text>().First();
                Assert.Equal("Changed3", firstText.Text);
            }
            File.Delete(testDocxFile);
            #endregion

            #region PresentationDocument.Open test
            string testPptxFile = "autosave.pptx";
            PrepareTestFile(testPptxFile, TestFileStreams.autosave);
            s.AutoSave = false;
            using (var doc = PresentationDocument.Open(testPptxFile, true, s))
            {
                // do something, and changes should not be saved.
                var slideMaster1 = doc.PresentationPart.GetPartById("rId1"); // Get slideMaster1.xml
                var texts = slideMaster1.RootElement.Descendants<a.Text>().Where(t => t.Text == "5/7/2009");
                foreach (var text in texts)
                {
                    text.Text = "5/9/2009";
                }
            }
            s.AutoSave = true;
            using (var doc = PresentationDocument.Open(testPptxFile, true, s))
            {
                var slideMaster1 = doc.PresentationPart.GetPartById("rId1"); // Get slideMaster1.xml
                // check first.
                var texts = slideMaster1.RootElement.Descendants<a.Text>().Where(t => t.Text == "5/9/2009");
                Assert.True(texts.Count() == 0);
                // change and save.
                texts = slideMaster1.RootElement.Descendants<a.Text>().Where(t => t.Text == "5/7/2009");
                foreach (var text in texts)
                {
                    text.Text = "5/9/2009";
                }
            }
            using (var pptxStream = new FileStream(testPptxFile, FileMode.Open, FileAccess.ReadWrite))
            using (var doc = PresentationDocument.Open(pptxStream, true))
            {
                var slideMaster1 = doc.PresentationPart.GetPartById("rId1"); // Get slideMaster1.xml
                // check first.
                var texts = slideMaster1.RootElement.Descendants<a.Text>().Where(t => t.Text == "5/9/2009");
                Assert.True(texts.Count() > 0);
                // change and save.
                foreach (var text in texts)
                {
                    text.Text = "5/10/2009";
                }
            }
            using (var pptxPackage = System.IO.Packaging.Package.Open(testPptxFile))
            using (var doc = PresentationDocument.Open(pptxPackage, s))
            {
                var slideMaster1 = doc.PresentationPart.GetPartById("rId1"); // Get slideMaster1.xml
                // check first.
                var texts = slideMaster1.RootElement.Descendants<a.Text>().Where(t => t.Text == "5/10/2009");
                Assert.True(texts.Count() > 0);
                // change and save.
                foreach (var text in texts)
                {
                    text.Text = "5/11/2009";
                }
            }
            using (var doc = PresentationDocument.Open(testPptxFile, false))
            {
                var slideMaster1 = doc.PresentationPart.GetPartById("rId1"); // Get slideMaster1.xml
                // check first.
                var texts = slideMaster1.RootElement.Descendants<a.Text>().Where(t => t.Text == "5/11/2009");
                Assert.True(texts.Count() > 0);
            }
            File.Delete(testPptxFile);
            #endregion

            #region SpreadsheetDocument.Open test
            string testXlsxFile = "autosave.xlsx";
            PrepareTestFile(testXlsxFile, TestFileStreams.basicspreadsheet);
            s.AutoSave = false;
            using (var doc = SpreadsheetDocument.Open(testXlsxFile, true, s))
            {
                // do changes, and they should not be saved.
                var sharedStringsPart = doc.WorkbookPart.GetPartById("rId7");
                var fonts = sharedStringsPart.RootElement.Descendants<x.RunFont>().Where(e => e.Val == "宋体");
                foreach (var font in fonts)
                {
                    font.Val = "微软雅黑";
                }

            }
            s.AutoSave = true;
            using (var doc = SpreadsheetDocument.Open(testXlsxFile, true, s))
            {
                // Check first
                var sharedStringsPart = doc.WorkbookPart.GetPartById("rId7");
                var fonts = sharedStringsPart.RootElement.Descendants<x.RunFont>().Where(e => e.Val == "微软雅黑");
                Assert.True(fonts.Count() == 0);
                // do changes, and they should be saved.
                fonts = sharedStringsPart.RootElement.Descendants<x.RunFont>().Where(e => e.Val == "宋体");
                foreach (var font in fonts)
                {
                    font.Val = "微软雅黑";
                }
            }
            using (var xlsxStream = new FileStream(testXlsxFile, FileMode.Open, FileAccess.ReadWrite))
            using (var doc = SpreadsheetDocument.Open(xlsxStream, true))
            {
                var sharedStringsPart = doc.WorkbookPart.GetPartById("rId7");
                var fonts = sharedStringsPart.RootElement.Descendants<x.RunFont>().Where(e => e.Val == "微软雅黑");
                Assert.True(fonts.Count() > 0);
                foreach(var font in fonts)
                {
                    font.Val = "仿宋";
                }
            }
            using (var xlsxPackage = System.IO.Packaging.Package.Open(testXlsxFile))
            using (var doc = SpreadsheetDocument.Open(xlsxPackage, s))
            {
                var sharedStringsPart = doc.WorkbookPart.GetPartById("rId7");
                var fonts = sharedStringsPart.RootElement.Descendants<x.RunFont>().Where(e => e.Val == "仿宋");
                Assert.True(fonts.Count() > 0);
                foreach (var font in fonts)
                {
                    font.Val = "楷体";
                }
            }
            using (var doc = SpreadsheetDocument.Open(testXlsxFile, false))
            {
                var sharedStringsPart = doc.WorkbookPart.GetPartById("rId7");
                var fonts = sharedStringsPart.RootElement.Descendants<x.RunFont>().Where(e => e.Val == "楷体");
                Assert.True(fonts.Count() > 0);
            }
            File.Delete(testXlsxFile);
            #endregion
        }
        //private WorkbookPart
        public CustomSpreadsheet(string path)
        {
            if (!System.IO.File.Exists(path))
            {
                //this.spreadsheet = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook);
                try
                {
                    this.spreadsheet = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook);
                }
                catch (Exception ex)
                {
                    this.spreadsheet = null;
                    return;
                }


                WorkbookPart workbookPart = this.spreadsheet.AddWorkbookPart();
                workbookPart.Workbook = new Workbook();
                this.workbook         = workbookPart;

                WorksheetPart worksheetPart = workbookPart.AddNewPart <WorksheetPart>();
                worksheetPart.Worksheet = new Worksheet(new SheetData());

                Sheets sheets = this.spreadsheet.WorkbookPart.Workbook.AppendChild <Sheets>(new Sheets());
                Sheet  sheet  = new Sheet()
                {
                    Id = this.spreadsheet.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1"
                };
                sheets.Append(sheet);
                //this.Save();
                this.Save();
                //this.Close();
            }
            else
            {
                OpenSettings openSettings = new OpenSettings();
                openSettings.MarkupCompatibilityProcessSettings =
                    new MarkupCompatibilityProcessSettings(
                        MarkupCompatibilityProcessMode.ProcessAllParts,
                        FileFormatVersions.Office2013
                        );
                try
                {
                    this.spreadsheet = SpreadsheetDocument.Open(path, true, openSettings);
                }
                catch (Exception ex)
                {
                    this.spreadsheet = null;
                }
                if (this.spreadsheet.GetPartsCountOfType <WorkbookPart>() > 0)
                {
                    this.workbook = this.spreadsheet.WorkbookPart;
                }
                else
                {
                    this.workbook = this.spreadsheet.AddWorkbookPart();
                }
                if (this.workbook == null)
                {
                    this.workbook          = this.spreadsheet.AddWorkbookPart();
                    this.workbook.Workbook = new Workbook();
                    this.InsertWorksheet();
                }
                if (this.workbook.GetPartsCountOfType <SharedStringTablePart>() > 0)
                {
                    this.sharedStrings = this.workbook.GetPartsOfType <SharedStringTablePart>().First();
                }
                if (this.workbook.GetPartsCountOfType <CalculationChainPart>() > 0)
                {
                    this.calcChain = this.workbook.GetPartsOfType <CalculationChainPart>().First();
                }
            }
        }
Example #13
0
        public void MCSave()
        {
            string file = "mcdoc.docx";
            CopyFileStream(TestFileStreams.mcdoc, file);

            //didn't process whole package ,should not process style part
            OpenSettings settings = new OpenSettings();
            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true,settings ))
            {
                OpenXmlPart target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root = target.RootElement;
            }

            //open in full mode, style part still has MC
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true))
            {
                OpenXmlPart target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root = target.RootElement;
                OpenXmlElement p1 = null;    
                p1 = root.FirstChild.FirstChild;
                //should throw exception
                var attrs = p1.GetAttributes();
                Assert.Equal(3, attrs.Count);

                target = testDocument.MainDocumentPart.StyleDefinitionsPart;
                root = target.RootElement;
                var rprDefault = root.FirstChild.FirstChild;
                Assert.Equal(2, rprDefault.GetAttributes().Count);
            }


            //process whole package ,should process style part
            
            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root = target.RootElement;
                
            }

            //open in full mode, style part has no MC
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true))
            {
                OpenXmlPart target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root = target.RootElement;

                OpenXmlElement p1 = null;
                p1 = root.FirstChild.FirstChild;
                Assert.Equal(3, p1.GetAttributes().Count);

                target = testDocument.MainDocumentPart.StyleDefinitionsPart;
                root = target.RootElement;
                var rprDefault = root.FirstChild.FirstChild;
                Assert.Equal(1, rprDefault.GetAttributes().Count);
            }
            System.IO.File.Delete(file);
        }
Example #14
0
 public OpenWindowViewModel(OpenSettings settings)
 {
     OpenCreate    = settings.Method;
     DirectoryPath = settings.MapsetPath;
     RememberPath  = settings.Remember;
 }
Example #15
0
        public void LoadACB()
        {
            string file = "mcdoc.docx";
            CopyFileStream(TestFileStreams.mcdoc, file);

            OpenSettings settings = new OpenSettings();
            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root = target.RootElement;

                var run = root.FirstChild.FirstChild.FirstChild.NextSibling();
                var secondele = run.FirstChild.NextSibling();

                root.Save();

                Assert.True(secondele is DocumentFormat.OpenXml.Wordprocessing.Picture);

            }
            System.IO.File.Delete(file);
        }
Example #16
0
        public void LoadACB2()
        {
            string file = "mcppt.pptx";
            CopyFileStream(TestFileStreams.mcppt, file);
            OpenSettings settings = new OpenSettings();
            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using(PresentationDocument doc = PresentationDocument.Open(file, true, settings ))
            {
                OpenXmlPart target = doc.PresentationPart.TableStylesPart;
                OpenXmlPartRootElement root = target.RootElement;

                var ele = root.FirstChild;
                Assert.True(ele is DocumentFormat.OpenXml.Drawing.TableStyleEntry);
                var attr = ele.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                Assert.Equal("1", attr.Value);
                Assert.True(ele is DocumentFormat.OpenXml.Drawing.TableStyleEntry);

                ele = ele.NextSibling();
                attr = ele.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                Assert.Equal("2", attr.Value);
                Assert.True(ele is DocumentFormat.OpenXml.Drawing.TableStyleEntry);

                ele = ele.NextSibling();
                attr = ele.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                Assert.Equal("3", attr.Value);
                Assert.True(ele is DocumentFormat.OpenXml.Drawing.TableStyleEntry);

                ele = ele.NextSibling();
                attr = ele.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                Assert.Equal("4", attr.Value);
                Assert.True(ele is DocumentFormat.OpenXml.Drawing.TableStyleEntry);

                ele = ele.NextSibling();
                Assert.Equal(null, ele);

                root.Save();

            }
            System.IO.File.Delete(file);
        }
Example #17
0
        public void LoadProcessContent()
        {
            string file = "mcexcel.docx";
            CopyFileStream(TestFileStreams.MCExecl, file);
            OpenSettings settings = new OpenSettings();
            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (SpreadsheetDocument doc = SpreadsheetDocument.Open(file,true,settings))
            {
                OpenXmlPart target = doc.WorkbookPart.SharedStringTablePart;
                OpenXmlPartRootElement root = target.RootElement;
                var si = root.FirstChild;
                Assert.Equal(0, si.ExtendedAttributes.Count());

                Assert.Equal(3, si.ChildElements.Count);

                var t = si.FirstChild;
                var attr = t.GetAttribute("a", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                Assert.Equal("a", attr.Value);
                attr = t.GetAttribute("b", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                Assert.Equal("b", attr.Value);

                Assert.Equal(2, t.ExtendedAttributes.Count());

            }
            System.IO.File.Delete(file);
        }
Example #18
0
        public void LoadPreserveAttr()
        {
            string file = "mcdoc.docx";
            CopyFileStream(TestFileStreams.mcdoc, file);
            OpenSettings settings = new OpenSettings();
            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root = target.RootElement;
                var ppr = root.FirstChild.FirstChild.FirstChild;

                var attr = ppr.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
                Assert.Equal("myattr", attr.Value);

                var space = ppr.FirstChild;
                attr = space.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
                Assert.Equal("myattr", attr.Value);

                Assert.Equal(1, space.ExtendedAttributes.Count());

                var r = ppr.NextSibling();
                attr = r.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
                Assert.Equal("myattr", attr.Value);
                Assert.Equal(1, r.ExtendedAttributes.Count());

                var rpr = r.FirstChild;
                attr = rpr.GetAttribute("myanotherAttr", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
                Assert.Equal("anotherattr", attr.Value);
                Assert.Equal(1, r.ExtendedAttributes.Count());

            }
            System.IO.File.Delete(file);
        }
Example #19
0
        public void LoadIgnorable()
        {
            string file = "mcdoc.docx";
            CopyFileStream(TestFileStreams.mcdoc, file);

            //using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, false, DocumentFormat.OpenXml.MCMode.Full, false))
            //using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, false))
            //{
            //    OpenXmlPart target = testDocument.MainDocumentPart;
            //    OpenXmlPartRootElement root = target.RootElement;
            //    OpenXmlElement p = root.FirstChild.FirstChild;
            //    var attr = p.GetAttribute("editId", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
            //    Assert.Equal("w14", attr.Prefix);
            //}

            OpenXmlElement p1 = null;
            OpenSettings settings = new OpenSettings();            
            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root = target.RootElement;

                p1 = root.FirstChild.FirstChild;
                root.Save();
            }
            //should throw exception
            Assert.Throws<KeyNotFoundException>(() =>
                {
                    p1.GetAttribute("editId", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
                });
            System.IO.File.Delete(file);
        }
Example #20
0
 public void W012_MarkupCompat_ProcessAllParts()
 {
     var docName = "Hyperlink.docx";
                 var ba = File.ReadAllBytes(Path.Combine(TestUtil.SourceDir.FullName, docName));
     using (MemoryStream ms = new MemoryStream())
     {
         ms.Write(ba, 0, ba.Length);
         OpenSettings openSettings = new OpenSettings();
         openSettings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(
             MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2013);
         using (WordprocessingDocument doc = WordprocessingDocument.Open(ms, true, openSettings))
         {
             OpenXmlValidator validator = new OpenXmlValidator(FileFormatVersions.Office2013);
             int cnt = validator.Validate(doc).Count();
             Assert.Equal(0, cnt);
         }
     }
 }
Example #21
0
        public void MCMustUnderstand()
        {
            string file = "mcdoc.docx";
            CopyFileStream(TestFileStreams.mcdoc, file);
            OpenSettings settings = new OpenSettings();
            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root = target.RootElement;
                root.FirstChild.MCAttributes = new MarkupCompatibilityAttributes();
                root.FirstChild.MCAttributes.MustUnderstand = "w14";
                var run = root.FirstChild.FirstChild.FirstChild.NextSibling();
                var secondele = run.FirstChild.NextSibling();
                Assert.True(secondele is DocumentFormat.OpenXml.Wordprocessing.Picture);
            }

            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart target = testDocument.MainDocumentPart;
                //should throw exception here
                Assert.Throws<NamespaceNotUnderstandException>(() =>
                {
                    OpenXmlPartRootElement root = target.RootElement;
                });
            }
            System.IO.File.Delete(file);
        }
Example #22
0
        private static WmlDocument PreProcessMarkup(WmlDocument source, int startingIdForFootnotesEndnotes)
        {
            // open and close to get rid of MC content
            using (var ms = new MemoryStream())
            {
                ms.Write(source.DocumentByteArray, 0, source.DocumentByteArray.Length);
                var os = new OpenSettings
                {
                    MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(
                        MarkupCompatibilityProcessMode.ProcessAllParts,
                        FileFormatVersions.Office2007)
                };

                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true, os))
                {
                    OpenXmlPartRootElement unused = wDoc.MainDocumentPart.RootElement;
                    if (wDoc.MainDocumentPart.FootnotesPart != null)
                    {
                        // contrary to what you might think, looking at the API, it is necessary to access the root element of each part to cause
                        // the SDK to process MC markup.
                        OpenXmlPartRootElement unused1 = wDoc.MainDocumentPart.FootnotesPart.RootElement;
                    }

                    if (wDoc.MainDocumentPart.EndnotesPart != null)
                    {
                        OpenXmlPartRootElement unused1 = wDoc.MainDocumentPart.EndnotesPart.RootElement;
                    }
                }

                source = new WmlDocument(source.FileName, ms.ToArray());
            }

            // open and close to get rid of MC content
            using (var ms = new MemoryStream())
            {
                ms.Write(source.DocumentByteArray, 0, source.DocumentByteArray.Length);
                var os = new OpenSettings
                {
                    MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(
                        MarkupCompatibilityProcessMode.ProcessAllParts,
                        FileFormatVersions.Office2007)
                };

                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true, os))
                {
                    TestForInvalidContent(wDoc);
                    RemoveExistingPowerToolsMarkup(wDoc);

                    // Removing content controls, field codes, and bookmarks is a no-no for many use cases.
                    // We need content controls, e.g., on the title page. Field codes are required for
                    // automatic cross-references, which require bookmarks.
                    // TODO: Revisit
                    var msSettings = new SimplifyMarkupSettings
                    {
                        RemoveBookmarks = true,

                        AcceptRevisions = false,
                        RemoveComments  = true,

                        RemoveContentControls = true,
                        RemoveFieldCodes      = true,

                        RemoveGoBackBookmark        = true,
                        RemoveLastRenderedPageBreak = true,
                        RemovePermissions           = true,
                        RemoveProof       = true,
                        RemoveSmartTags   = true,
                        RemoveSoftHyphens = true,
                        RemoveHyperlinks  = true
                    };
                    MarkupSimplifier.SimplifyMarkup(wDoc, msSettings);
                    ChangeFootnoteEndnoteReferencesToUniqueRange(wDoc, startingIdForFootnotesEndnotes);
                    AddUnidsToMarkupInContentParts(wDoc);
                    AddFootnotesEndnotesParts(wDoc);
                    FillInEmptyFootnotesEndnotes(wDoc);
                }

                return(new WmlDocument(source.FileName, ms.ToArray()));
            }
        }
Example #23
0
        public void ParticalProperty()
        {
            string file = "simpleSdt.docx";
            CopyFileStream(TestFileStreams.simpleSdt, file);
            OpenSettings settings = new OpenSettings();
            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings ))
            {
                OpenXmlPart target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root = target.RootElement;
                var sdt = root.FirstChild.FirstChild as SdtBlock;
                SdtProperties sdtpr = sdt.SdtProperties;

                var alias = sdt.SdtProperties.FirstChild as SdtAlias;
                Assert.Equal("SDT1", alias.Val.Value);
                alias.Val.Value = "newsdt";
            }

            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings ))
            {
                OpenXmlPart target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root = target.RootElement;
                var sdt = root.FirstChild.FirstChild as SdtBlock;
                SdtProperties sdtpr = sdt.SdtProperties;

                var alias = sdt.SdtProperties.FirstChild as SdtAlias;
                Assert.Equal("newsdt", alias.Val.Value);
            }
            System.IO.File.Delete(file);
        }
Example #24
0
        public void W037_DocxCreation_Package_Settings()
        {
            var docName = "Document.docx";
            var fiSource = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, docName));
            var fiCopy = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, Guid.NewGuid().ToString() + ".docx"));
            File.Copy(fiSource.FullName, fiCopy.FullName);
            using (Package package = Package.Open(fiCopy.FullName, FileMode.Open, FileAccess.ReadWrite))
            {
                OpenSettings openSettings = new OpenSettings();
                openSettings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2013);
                using (WordprocessingDocument doc = WordprocessingDocument.Open(package, openSettings))
                {
                    var cnt = doc.MainDocumentPart.Document.Descendants().Count();
                    var s = doc.MarkupCompatibilityProcessSettings;

                    OpenXmlValidator v = new OpenXmlValidator(FileFormatVersions.Office2013);
                    var errs = v.Validate(doc);
                    Assert.Equal(450, errs.Count());
                }
            }
            if (TestUtil.DeleteTempFiles)
                fiCopy.Delete();
        }
Example #25
0
        public void Bug718314()
        {
            using(WordprocessingDocument doc = WordprocessingDocument.Create("tmp.docx", WordprocessingDocumentType.Document))
            {
                var mpart = doc.AddMainDocumentPart();
                mpart.Document = new Document();
                mpart.Document.Body = new Body();
                mpart.Document.Body.Append(new AlternateContent());
            }

            OpenSettings s = new OpenSettings();
            s.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2007);
            using(var doc = WordprocessingDocument.Open("tmp.docx", true, s))
            {
                Assert.Null(doc.MainDocumentPart.Document.Body.FirstChild);
            }
            System.IO.File.Delete("tmp.docx");
        }
        public void O15FileOpenTest()
        {
            string testXlsxFile = "Youtube.xlsx";

            OpenSettings settings2012 = new OpenSettings()
            {
                MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2013)
            };

            #region SpreadsheetDocument.O15FileOpen test
            PrepareTestFile(testXlsxFile, TestFileStreams.Youtube);
            try
            {
                // Well, if WebExtension is not integrated in the SDK, we can't even compile this unit test project...

                // Check if WebExtension in the test file is accessible.
                using (var doc = SpreadsheetDocument.Open(testXlsxFile, false, settings2012))
                {
                    var worksheetPart = doc.WorkbookPart.WorksheetParts.First();
                    WebExtensionPart webExtensionPart = worksheetPart.DrawingsPart.WebExtensionParts.First();

                    Assert.NotNull(webExtensionPart);
                }
            }
            catch
            {
                Assert.True(false); // Assert.Fail("Should not throw exception.");
            }

            File.Delete(testXlsxFile);
            #endregion
        }
Example #27
0
        public void Bug718316()
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Create("tmp.docx", WordprocessingDocumentType.Document))
            {
                var mpart = doc.AddMainDocumentPart();
                mpart.Document = new Document();
                mpart.Document.Body = new Body();
                var ac = new AlternateContent();
                mpart.Document.Body.Append(ac);
                var c = new AlternateContentChoice();
                c.AddNamespaceDeclaration("w13", "http://w13");
                c.Requires = "w13";
                ac.Append(c);
            }

            OpenSettings s = new OpenSettings();
            s.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2007);
            using (var doc = WordprocessingDocument.Open("tmp.docx", true, s))
            {
                Assert.Null(doc.MainDocumentPart.Document.Body.FirstChild);
            }
            System.IO.File.Delete("tmp.docx");
        }
Example #28
0
        public void DumpSheetRange <T>(T output, string filename, string sheetName, string firstCellName, string lastCellName) where T : TextWriter
        {
            // Create instance of OpenSettings
            OpenSettings openSettings = new OpenSettings
            {
                // Add the MarkupCompatibilityProcessSettings
                MarkupCompatibilityProcessSettings =
                    new MarkupCompatibilityProcessSettings(
                        MarkupCompatibilityProcessMode.ProcessAllParts,
                        FileFormatVersions.Office2013)
            };

            // Open the document with OpenSettings
            using (SpreadsheetDocument excelDocument =
                       SpreadsheetDocument.Open(filename,
                                                false,
                                                openSettings))
            {
                var    wbPart = excelDocument.WorkbookPart;
                Sheets sheets = wbPart.Workbook.Sheets;
                foreach (E sheetElem in sheets)
                {
                    foreach (A attr in sheetElem.GetAttributes())
                    {
                        output.Write("{0}: {1}\t", attr.LocalName, attr.Value);
                    }
                    output.WriteLine();
                }
                S sheet = wbPart.Workbook.Descendants <S>().Where(s => s.Name == sheetName).First();
                // Throw an exception if there is no sheet.
                if (sheet == null)
                {
                    throw new ArgumentException("sheetName is invalid for this workbook");
                }
                // Retrieve a reference to the worksheet part.
                WorksheetPart wsPart =
                    (WorksheetPart)wbPart.GetPartById(sheet.Id);

                W   worksheet   = wsPart.Worksheet;
                var stringTable =
                    wbPart.GetPartsOfType <SharedStringTablePart>()
                    .FirstOrDefault();

                uint   firstRowNum = ColumnComparer.GetRowIndex(firstCellName);
                uint   lastRowNum  = ColumnComparer.GetRowIndex(lastCellName);
                string firstColumn = ColumnComparer.GetColumnName(firstCellName);
                string lastColumn  = ColumnComparer.GetColumnName(lastCellName);

                string headers = firstColumn;
                while (ColumnComparer.CompareColumn(headers, lastColumn) <= 0)
                {
                    output.Write("{0}\t", headers);
                    headers = ColumnComparer.NextColumn(headers);
                }
                output.WriteLine();

                //// Iterate through the cells within the range and do whatever.
                foreach (int row in Enumerable.Range((int)firstRowNum, (int)lastRowNum))
                {
                    string col = firstColumn;
                    while (ColumnComparer.IsColumnInRange(firstColumn, lastColumn, col))
                    {
                        var cellRef = String.Format("{0}{1}", col, row);
                        var cell    = wsPart.Worksheet.Descendants <Cell>().Where(c => c.CellReference == cellRef).FirstOrDefault();
                        output.Write("{0}\t", DecodedCell(cell, stringTable));
                        col = ColumnComparer.NextColumn(col);
                    }
                    output.WriteLine();
                }
            }
        }
        public static void AddDataSpreadsheetWorkBook(string filepath, string col, uint rowNum, string text, CellValues type = CellValues.Number)
        {
            OpenSettings openSettings = new OpenSettings();

            openSettings.MarkupCompatibilityProcessSettings =
                new MarkupCompatibilityProcessSettings(
                    MarkupCompatibilityProcessMode.ProcessAllParts,
                    FileFormatVersions.Office2013
                    );

            SpreadsheetDocument spreadsheet = SpreadsheetDocument.Open(filepath, true, openSettings);

            WorkbookPart workbookPart = spreadsheet.GetPartsOfType <WorkbookPart>().First();
            //workbookPart.Workbook = new Workbook();

            WorksheetPart worksheetPart = workbookPart.GetPartsOfType <WorksheetPart>().First();
            //worksheetPart.Worksheet = new Worksheet(new SheetData());

            //Sheets sheets = spreadsheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
            //Sheet sheet = new Sheet() { Id = spreadsheet.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };

            //sheets.Append(sheet);

            //  Adding data:
            SheetData sheetData = worksheetPart.Worksheet.GetFirstChild <SheetData>();
            //  Add a row:
            Row row;

            //row = new Row() { RowIndex = 1 };
            //sheetData.Append(row);
            try
            {
                row = (Row)sheetData.ElementAt((int)rowNum);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                row = new Row()
                {
                    RowIndex = new UInt32Value((uint)rowNum)
                };
                sheetData.Append(row);
            }
            //Row Row2nd = (Row)sheetData.ElementAt(100);

            //  Find the A1 cell in the first Cell
            Cell   refCell      = null;
            string cellLocation = col + rowNum.ToString();

            foreach (Cell cell in row.Elements <Cell>())
            {
                if (string.Compare(cell.CellReference.Value, cellLocation, true) > 0)
                {
                    refCell = cell;
                    break;
                }
            }
            Cell newCell = new Cell()
            {
                CellReference = cellLocation
            };

            row.InsertBefore(newCell, refCell);
            //row.InsertBefore()
            //  Set the cell value:
            newCell.CellValue = new CellValue(text);
            //Can be Shared String here:

            newCell.DataType = new EnumValue <CellValues>(type);

            workbookPart.Workbook.Save();
            spreadsheet.Close();
        }
Example #30
0
        public void Bug537858()
        {
            string file = "temp.xlxs";
            CopyFileStream(TestFileStreams.animation, file);
            OpenSettings s = new OpenSettings();
            s.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2007);
            using (PresentationDocument doc = PresentationDocument.Open(file, true, s))
            {
                var sp = doc.PresentationPart.GetPartById("rId4") as SlidePart;
                Transition t = sp.Slide.ChildElements[2] as Transition;
                Assert.True(t.ExtendedAttributes.Count() == 0);
                Assert.True(t.NamespaceDeclarations.Count() == 1);

            }
        }
Example #31
0
        public string CreatePDFReport(dynamic reportData, string serverAddr)
        {
            var        jsonStr   = reportData.GetValue("stats").ToString();
            string     mapURL    = reportData.GetValue("mapURL").ToString();
            ReportData data      = ReportData.FromJson(jsonStr);
            string     directory = Directory.GetCurrentDirectory();
            var        setting   = new OpenSettings();

            setting.AutoSave = false;
            var         dateUtils        = new DateUtils();
            StringUtils stringUtils      = new StringUtils();
            ReportUtils ReportUtils      = new ReportUtils();
            string      fileName         = config("filePrefix") + "_" + DateTime.Now.ToString("MM-dd-yyyy") + "_" + DateTime.Now.ToString("HHmmss");
            string      tempFileName     = directory + "\\wwwroot\\reports\\" + fileName + ".docx";
            string      templateFileName = directory + "\\wwwroot\\template\\" + config("template");

            try  {
                File.Copy(templateFileName, tempFileName);
            } catch (Exception e) { throw(e); }

            ReportUtils.ReplaceImage(tempFileName, mapURL, config("mapImageId"));

            SummaryReportResults summary = data.SummaryReportResults;

            // get the individual summary objects for replacing to the openxml later
            SummaryResult[] summaryArray = data.SummaryResults;
            SummaryResult   airquality   = summaryArray.Where(s => s.EcosystemService == "airquality").ToArray()[0];
            SummaryResult   biodiversity = summaryArray.Where(s => s.EcosystemService == "biodiversity").ToArray()[0];
            SummaryResult   carbon       = summaryArray.Where(s => s.EcosystemService == "carbon").ToArray()[0];
            SummaryResult   cultural     = summaryArray.Where(s => s.EcosystemService == "cultural").ToArray()[0];
            SummaryResult   watershed    = summaryArray.Where(s => s.EcosystemService == "watershed").ToArray()[0];
            SummaryResult   total        = summaryArray.Where(s => s.EcosystemService == "total").ToArray()[0];

            //Create report params dictionary
            Dictionary <string, string> reportParamsDict = new Dictionary <string, string>();

            reportParamsDict.Add("ZZAoiForestAcresZZ", summary.AoiForestAcres);
            reportParamsDict.Add("ZZAoiUrbanAcresZZ", "" + summary.AoiUrbanAcres);
            reportParamsDict.Add("ZZAoiRuralAcresZZ", summary.AoiRuralAcres);

            reportParamsDict.Add("ZZairqualityAvgZZ", airquality.ForestAverageValue);
            reportParamsDict.Add("ZZairqualityTotalZZ", airquality.ForestTotalValue + " thousand");

            reportParamsDict.Add("ZZbiodiversityAvgZZ", biodiversity.ForestAverageValue);
            reportParamsDict.Add("ZZbiodiversityTotalZZ", biodiversity.ForestTotalValue + " thousand");

            reportParamsDict.Add("ZZcarbonAvgZZ", carbon.ForestAverageValue);
            reportParamsDict.Add("ZZcarbonTotalZZ", carbon.ForestTotalValue + " thousand");

            reportParamsDict.Add("ZZculturalAvgZZ", cultural.ForestAverageValue);
            reportParamsDict.Add("ZZculturalTotalZZ", cultural.ForestTotalValue + " thousand");

            reportParamsDict.Add("ZZwatershedAvgZZ", watershed.ForestAverageValue);
            reportParamsDict.Add("ZZwatershedTotalZZ", watershed.ForestTotalValue + " thousand");

            reportParamsDict.Add("ZZtotalAvgZZ", total.ForestAverageValue);
            reportParamsDict.Add("ZZtotalTotalZZ", total.ForestTotalValue);
            reportParamsDict.Add("ZZtotalTotalThousandZZ", total.ForestTotalValue + " thousand");

            string[] ecosystems = new string[] { "airquality", "biodiversity", "carbon", "cultural", "watershed", "total" };
            foreach (string eco in ecosystems)
            {
                reportParamsDict.Add("ZZ" + eco + "UrbanZZ", (string)summary[eco + "_urbanThousandDollarsPerYear"]);
                reportParamsDict.Add("ZZ" + eco + "RuralZZ", (string)summary[eco + "_ruralThousandDollarsPerYear"]);
                reportParamsDict.Add("ZZ" + eco + "Total1ZZ", (string)summary[eco + "_totalThousandDollarsPerYear"]);
            }

            stringUtils.SearchAndReplace(tempFileName, reportParamsDict);
            DocxToPDF PDFConvertor = new DocxToPDF();

            PDFConvertor.ConvertDocxToPDF(tempFileName);
            string pdfPath = serverAddr + "reports/" + fileName + ".pdf";;

            File.Delete(tempFileName);
            return(pdfPath);
        }
Example #32
0
        public void MCSave()
        {
            // Didn't process whole package, should not process style part
            var settings = new OpenSettings
            {
                MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007),
            };

            using (var stream = GetStream(TestFiles.Mcdoc, true))
            {
                using (var testDocument = WordprocessingDocument.Open(stream, true, settings))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement root   = target.RootElement;
                }

                stream.Position = 0;

                // Open in full mode, style part still has MC
                using (var testDocument = WordprocessingDocument.Open(stream, true))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement root   = target.RootElement;
                    OpenXmlElement         p1     = null;
                    p1 = root.FirstChild.FirstChild;

                    // should throw exception
                    var attrs = p1.GetAttributes();
                    Assert.Equal(3, attrs.Count);

                    target = testDocument.MainDocumentPart.StyleDefinitionsPart;
                    root   = target.RootElement;
                    var rprDefault = root.FirstChild.FirstChild;
                    Assert.Equal(2, rprDefault.GetAttributes().Count);
                }

                stream.Position = 0;

                // Process whole package, should process style part
                settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2007);
                using (var testDocument = WordprocessingDocument.Open(stream, true, settings))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement root   = target.RootElement;
                }

                stream.Position = 0;

                // Open in full mode, style part has no MC
                using (var testDocument = WordprocessingDocument.Open(stream, true))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement root   = target.RootElement;

                    OpenXmlElement p1 = null;
                    p1 = root.FirstChild.FirstChild;
                    Assert.Equal(3, p1.GetAttributes().Count);

                    target = testDocument.MainDocumentPart.StyleDefinitionsPart;
                    root   = target.RootElement;
                    var rprDefault = root.FirstChild.FirstChild;
                    Assert.Equal(1, rprDefault.GetAttributes().Count);
                }
            }
        }
Example #33
0
 private void ButtonSettingsClick(object sender, RoutedEventArgs e)
 {
     OpenSettings?.Invoke(sender, e);
 }
Example #34
0
        public static ExcelDocument Open(Package package, OpenSettings openSettings)
        {
            SpreadsheetDocument doc = SpreadsheetDocument.Open(package, openSettings);

            return(new ExcelDocument(doc));
        }
Example #35
0
        public static PresentationDocument OpenPresentation(Stream stream, bool isEditable, OpenSettings openSettings)
        {
            try
            {
                return(PresentationDocument.Open(stream, isEditable, openSettings));
            }
            catch (OpenXmlPackageException e)
            {
                if (!e.ToString().Contains("Invalid Hyperlink"))
                {
                    throw;
                }

                FixInvalidUri(stream);
                return(PresentationDocument.Open(stream, isEditable, openSettings));
            }
        }
Example #36
0
 public static ExcelDocument Open(Stream stream, bool isEditable, OpenSettings openSettings)
 {
     return(new ExcelDocument(SpreadsheetDocument.Open(stream, isEditable, openSettings)));
 }
        public async Task UploadAndReadChunkedExcelDocumentFromBlobStorage()
        {
            var app = new ApplicationFactory((IServiceCollection services) =>
            {
                services.Add(new ServiceDescriptor(typeof(Files.IFileService), typeof(Files.AzureBlobStorageFileService), ServiceLifetime.Transient));
            });

            string sampleFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\..\Measures\HPHCI");

            string[] files = Directory.GetFiles(sampleFolder);

            using (var scope = app.CreateScope())
            {
                var    service    = (Files.IFileService)scope.ServiceProvider.GetService(typeof(Files.IFileService));
                string identifier = Guid.NewGuid().ToString("D");

                try
                {
                    string file = files.First();


                    FileInfo fi = new FileInfo(file);
                    using (var fs = fi.OpenRead())
                    {
                        int bytesToRead = Convert.ToInt32(fs.Length / 2);
                        var buffer      = new byte[bytesToRead];
                        fs.Read(buffer, 0, bytesToRead);

                        var ms = new MemoryStream(buffer);
                        ms.Position = 0;

                        Console.WriteLine($"Writing excel file: \"{ file }\" to Azure Blob Storage. Total Length:{ fi.Length }. Chunk: 0, length:{ bytesToRead }");
                        await service.WriteToStreamAsync(identifier, 0, ms);

                        Console.WriteLine($"Writing excel file: \"{ file }\" to Azure Blob Storage. Total Length:{ fi.Length }. Chunk: 1, length:{ fs.Length - bytesToRead }");
                        await service.WriteToStreamAsync(identifier, 1, fs);
                    }


                    //Console.WriteLine($"Reading excel document: \"{ file }\" from Azure Blob Storage.");
                    //using (var stream = service.ReturnTempFileStream(identifier))
                    //{
                    //    string filename = Path.Combine(@"z:\shared\dqmtemp", identifier + ".xlsx");
                    //    using (var tempFS = File.Open(filename, FileMode.OpenOrCreate))
                    //    {
                    //        long bytesRead = 0;
                    //        do
                    //        {
                    //            byte[] buffer = new byte[32];
                    //            bytesRead = stream.Read(buffer, 0, 32);
                    //            if (bytesRead > 0)
                    //            {
                    //                tempFS.Write(buffer, 0, Convert.ToInt32(bytesRead));
                    //            }
                    //        } while (bytesRead > 0);

                    //        tempFS.Flush();

                    //        Console.WriteLine($"File size of downloaded file is:{ new FileInfo(filename).Length }");
                    //    }
                    //}


                    List <string> errors = new List <string>();
                    DQM.Models.MeasureSubmissionViewModel measure = null;


                    OpenSettings openSettings = new OpenSettings {
                        AutoSave = false
                    };

                    Console.WriteLine($"Reading excel document: \"{ file }\" from Azure Blob Storage.");
                    using (var stream = service.ReturnTempFileStream(identifier))
                        using (var ms = new MemoryStream())
                        {
                            //long bytesRead = 0;
                            //do
                            //{
                            //    byte[] buffer = new byte[32];
                            //    bytesRead = stream.Read(buffer, 0, 32);
                            //    if (bytesRead > 0)
                            //    {
                            //        ms.Write(buffer, 0, Convert.ToInt32(bytesRead));
                            //    }
                            //} while (bytesRead > 0);

                            //ms.Position = 0;

                            Console.WriteLine($"Total length of document reported by Azure Blob Storage:{ stream.Length }");
                            using (var document = SpreadsheetDocument.Open(stream, false, openSettings))
                            {
                                var reader = new ASPE.DQM.Utils.MeasuresExcelReader(document);
                                measure = reader.Convert(errors);

                                document.Close();
                            }
                        }
                }
                finally
                {
                    await service.DeleteTempFileChunkAsync(identifier);
                }
            }
        }