Beispiel #1
0
        /// <summary>
        /// Merge or update input data into Excel File
        /// </summary>
        public static int UpdateInputDataIntoExcelFile(string excelFileName, List <MembershipData> inputDataList)
        {
            int updatedRows = 0;

            using (SpreadsheetDocument document = SpreadsheetDocument.Open(excelFileName, true))
            {
                var workSheets    = document.WorkbookPart.Workbook.Descendants <Sheet>();
                var sharedStrings = document.WorkbookPart.SharedStringTablePart.SharedStringTable;

                var firstSheetId   = workSheets.First().Id;
                var firstSheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(firstSheetId);
                var firstWorksheet = firstSheetPart.Worksheet;
                var isHeader       = true;

                foreach (Row row in firstWorksheet.Descendants <Row>())
                {
                    if (isHeader)
                    {
                        UpdateMembershipPropertiesWithColumnIndex(sharedStrings, row, inputDataList);
                    }
                    else
                    {
                        updatedRows = updatedRows + UpdateWorksheetRowFromMembershipData(sharedStrings, row, inputDataList);
                    }
                    isHeader = false;
                }
                if (updatedRows > 0)
                {
                    // Save the worksheet.
                    firstSheetPart.Worksheet.Save();
                    document.Save();
                }
            }
            return(updatedRows);
        }
        public static uint GetOrSetErrorFillID(SpreadsheetDocument workdocument)
        {
            WorkbookStylesPart stylesPart = workdocument.WorkbookPart.WorkbookStylesPart;
            Fills fills    = stylesPart.Stylesheet.Fills;
            Fill  cellFill = null;
            uint  fillId   = 0;

            if (!ExistsRedFillPattern(fills, ref cellFill, ref fillId))
            {
                Fill        newErrorFill    = new Fill();
                PatternFill newErrorPattern = new PatternFill()
                {
                    PatternType = PatternValues.Solid
                };
                newErrorPattern.AppendChild(new ForegroundColor()
                {
                    Rgb = "FFFF0000"
                });
                newErrorPattern.AppendChild(new BackgroundColor()
                {
                    Indexed = 64
                });
                newErrorFill.AppendChild(newErrorPattern);
                fills.AppendChild(newErrorFill);
                fills.Count++;
            }
            workdocument.Save();
            ErrorStyleFillId = fillId;
            return(fillId);
        }
        public void ClearText()
        {
            _filePath = @"C:\Users\vemal\Documents\DevHandover_corrected.xlsm";
            using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(_filePath, true))
            {
                _sheetName                = "Sheet1"; //Sheet name should be changed to dynamic
                _mainSheetData            = GetSingleSheetByName(spreadsheetDocument, _sheetName);
                _mainSheetData            = GetRowsAndStringTableFromSheet(_mainSheetData);
                _mainSheetObjectToCompare = GetAllNamesFromSheet(_mainSheetData.sharedStringTable, _mainSheetData.Rows);

                _sheetName      = "EBAttributes";
                _sheetData      = GetSingleSheetByName(spreadsheetDocument, _sheetName);
                _sheetData      = GetRowsAndStringTableFromSheet(_sheetData);
                _newSheetObject = GetAllSimilerData(_mainSheetObjectToCompare, _sheetData.sharedStringTable, _sheetData.Rows);

                _sheetName      = "API";
                _sheetData      = GetSingleSheetByName(spreadsheetDocument, _sheetName);
                _sheetData      = GetRowsAndStringTableFromSheet(_sheetData);
                _newSheetObject = GetAllSimilerData(_mainSheetObjectToCompare, _sheetData.sharedStringTable, _sheetData.Rows);

                _sheetName      = "ISA";
                _sheetData      = GetSingleSheetByName(spreadsheetDocument, _sheetName);
                _sheetData      = GetRowsAndStringTableFromSheet(_sheetData);
                _newSheetObject = GetAllSimilerData(_mainSheetObjectToCompare, _sheetData.sharedStringTable, _sheetData.Rows);

                //DeleteSheet(_mainSheetData);
                var newSheet = CreateNewWorkSheet(spreadsheetDocument, "Sheet2");
                spreadsheetDocument.Save();
                AddrowsToNewWorkSheet(_newSheetObject, spreadsheetDocument);
            }
        }
Beispiel #4
0
 /// <summary>Save the edit values</summary>
 public void Save()
 {
     foreach (var sheet in this)
     {
         sheet.Save();
     }
     WorkbookPart.Workbook.Save();
     SpreadsheetDocument.Save();
 }
 public static void Save(SpreadsheetDocument document)
 {
     if (document is null)
     {
         throw new ArgumentNullException(nameof(document));
     }
     //document.WorkbookPart.Workbook.Save();
     document.Save();
 }
Beispiel #6
0
        public void Dispose()
        {
            foreach (var key in _sheets.Keys)
            {
                _sheets[key].Save();
            }

            _spreadsheetDocument.Save();
            _spreadsheetDocument.Dispose();
        }
Beispiel #7
0
        private void bgwRename_DoWork(object sender, DoWorkEventArgs e)
        {
            var            logs  = "";
            RenameMetadata meta  = e.Argument as RenameMetadata;
            int            i     = 0;
            int            total = meta.RootNodes.Count;

            foreach (TreeViewNode fileNode in meta.RootNodes)
            {
                if (fileNode.Text != fileNode.Tag.ToString())
                {
                    try
                    {
                        File.Move(meta.Path + fileNode.Tag.ToString(), meta.Path + fileNode.Text);
                    }
                    catch (IOException ex)
                    {
                        logs += $"Exception when renaming {fileNode.Tag.ToString()} to {fileNode.Text}" + Environment.NewLine;
                        logs += ex.Message + Environment.NewLine;
                    }
                }

                bool isAnySheetRenamed = false;
                foreach (TreeViewNode sheetNode in fileNode.Nodes)
                {
                    if (sheetNode.Text != sheetNode.Tag.ToString())
                    {
                        isAnySheetRenamed = true;
                    }
                }

                if (isAnySheetRenamed)
                {
                    using (SpreadsheetDocument document = SpreadsheetDocument.Open(meta.Path + fileNode.Text, true))
                    {
                        WorkbookPart wbPart = document.WorkbookPart;
                        foreach (Sheet sheet in wbPart.Workbook.Sheets)
                        {
                            foreach (TreeViewNode sheetNode in fileNode.Nodes)
                            {
                                if (sheetNode.Tag.ToString() == sheet.Name && sheetNode.Text != sheetNode.Tag.ToString())
                                {
                                    sheet.Name = sheetNode.Text;
                                }
                            }
                        }
                        document.Save();
                    }
                }

                int percentage = (i * 100) / total;
                bgwRename.ReportProgress(percentage, logs);
                i++;
            }
        }
Beispiel #8
0
        public Attachment AddFromList(string connString, string command)
        {
            SqlConnection sqlConnection = new SqlConnection(connString);
            SqlCommand    sqlCommand    = new SqlCommand(command, sqlConnection);

            sqlConnection.Open();
            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();

            MemoryStream        memoryStream = new MemoryStream();
            SpreadsheetDocument document     = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook);
            WorkbookPart        workbookPart = document.AddWorkbookPart();

            workbookPart.Workbook = new Workbook();

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

            worksheetPart.Worksheet = new Worksheet();

            Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
            Sheet  sheet  = new Sheet()
            {
                Id      = workbookPart.GetIdOfPart(worksheetPart),
                SheetId = 1,
                Name    = "Kullanıcılar"
            };

            sheets.Append(sheet);
            workbookPart.Workbook.Save();

            SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
            Row       row       = new Row();

            row.Append(getCell("Tam Adı", CellValues.String), getCell("Email", CellValues.String));
            sheetData.AppendChild(row);

            while (sqlDataReader.Read())
            {
                row = new Row();
                row.Append(getCell(sqlDataReader.GetString(0), CellValues.String),
                           getCell(sqlDataReader.GetString(1), CellValues.String));
                sheetData.AppendChild(row);
            }

            sqlConnection.Close();

            worksheetPart.Worksheet.Save();
            document.Save();
            document.Close();
            document.Dispose();

            memoryStream.Seek(0, SeekOrigin.Begin);
            Attachment attachment = new Attachment(memoryStream, "KullanıcıListesi.xlsx");

            return(attachment);
        }
        public void CsvToOpenDocumentSpreadsheet()
        {
            SpreadsheetDocument document = new SpreadsheetDocument();

            document.Load(AARunMeFirstAndOnce.inPutFolder + "CsvToOpenDocument.csv", new CsvImporter());
            Assert.IsTrue(document.Content.Count == 1, "Must contain objects.");
            using (IPackageWriter writer = new OnDiskPackageWriter())
            {
                document.Save(AARunMeFirstAndOnce.outPutFolder + "CsvToOpenDocument.ods", new OpenDocumentTextExporter(writer));
            }
        }
Beispiel #10
0
 /// <summary>
 /// Sets the document public properties
 /// </summary>
 /// <param name="document">SpreadSheetDocument reference</param>
 /// <param name="title">Document title</param>
 /// <param name="description">Document description</param>
 /// <param name="creator">Creator</param>
 /// <param name="category">Category</param>
 /// <param name="lastModifiedBy">Person that last modified</param>
 public static void SetProperties(this SpreadsheetDocument document, string title, string description = null, string creator = null, string category = null, string lastModifiedBy = null)
 {
     //Add Document properties
     document.PackageProperties.Title          = title ?? @"Reporte";
     document.PackageProperties.Creator        = creator ?? @"Israel Ch";
     document.PackageProperties.Category       = category ?? @"Reporte";
     document.PackageProperties.Description    = description ?? @"Reporte tipo listado";
     document.PackageProperties.LastModifiedBy = lastModifiedBy ?? @"Israel Ch";
     //Save all changes
     document.Save();
 }
        public string ExportData(List <Asset> data)
        {
            string path = Path.Combine(getPath(), "Reporte.xlsx");

            foreach (Sheet s in part.Workbook.Sheets)
            {
                insertData(data, s);
            }
            app.Save();
            app.Close();
            return(path);
        }
Beispiel #12
0
        public async static Task ToExcel <TData>(IEnumerable <TData> data, string path)
        {
            using (SpreadsheetDocument document = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook, true))
            {
                DataSet dataSet = new DataSet();
                dataSet.Tables.Add(await data.ToDataTable());

                await CreateExcel(dataSet, document);

                document.Save();
            }
        }
Beispiel #13
0
    public string WriteCellData(IDictionary <string, object> data)
    {
        var cellRefRegex = new Regex(@"^([a-zA-Z]*)(\d*)$");

        if (sharedStringTable == null)
        {
            sharedStringTable = workbookPart.AddNewPart <SharedStringTablePart>();
        }

        foreach (var key in data.Keys)
        {
            var sheetName = key.Split("!")[0];
            var cellRef   = key.Split("!")[1];

            WorksheetPart wsPart = null;
            var           sheet  = workbookPart.Workbook.Descendants <Sheet>().Where(s => s.Name == sheetName).FirstOrDefault();
            if (sheet == null)
            {
                wsPart = InsertWorksheet(workbookPart, sheetName);
            }
            else
            {
                wsPart = (WorksheetPart)(workbookPart.GetPartById(sheet.Id));
            }

            var cellRefMatch = cellRefRegex.Matches(cellRef).FirstOrDefault();
            var columnName   = cellRefMatch.Groups[1].Value;
            var rowIndex     = (uint)Int32.Parse(cellRefMatch.Groups[2].Value);

            var cell = InsertCellInWorksheet(columnName, rowIndex, wsPart);

            var value    = data[key];
            int strIndex = -1;
            if (value is string)
            {
                strIndex       = InsertSharedStringItem(value.ToString());
                cell.CellValue = new CellValue(strIndex.ToString());
                cell.DataType  = new EnumValue <CellValues>(CellValues.SharedString);
            }
            else
            {
                cell.CellValue = new CellValue(value.ToString());
            }
            wsPart.Worksheet.Save();
        }

        spreadsheet.WorkbookPart.Workbook.Save();
        spreadsheet.Save();
        spreadsheet.Close();
        spreadsheet.Dispose();

        return(Convert.ToBase64String(stream.ToArray()));
    }
        public void NewBasicChartThenSetTitle()
        {
            const string        expected = "Basic Chart";
            SpreadsheetDocument doc      = new SpreadsheetDocument();

            doc.New();
            Table table = new Table(doc, "tab1", "tab1");

            for (int i = 1; i <= 1; i++)
            {
                for (int j = 1; j <= 6; j++)
                {
                    Cell cell = table.CreateCell();
                    cell.OfficeValueType = "float";
                    Paragraph paragraph = new Paragraph(doc);
                    string    text      = (j + i - 1).ToString();
                    paragraph.TextContent.Add(new SimpleText(doc, text));
                    cell.Content.Add(paragraph);
                    cell.OfficeValueType = "string";
                    cell.OfficeValue     = text;
                    table.InsertCellAt(i, j, cell);
                }
            }
            Chart      basicChart = ChartBuilder.CreateChart(table, ChartTypes.line, "A4:F8");
            ChartTitle ct         = new ChartTitle(basicChart);

            //ct.InitTitle();
            ct.SetTitle(expected);
            Assert.AreEqual(expected, ((Paragraph)ct.Content[0]).TextContent[0].Text);
            basicChart.ChartTitle = ct;
            IContent chartTitleContent = basicChart.Content.Find(o => o is ChartTitle);

            if (chartTitleContent == null)
            {
                foreach (IContent iContent in basicChart.Content)
                {
                    if (iContent is ChartTitle)
                    {
                        chartTitleContent = iContent;
                    }
                }
            }
            Assert.AreEqual(expected, ((Paragraph)((ChartTitle)chartTitleContent).Content[0]).TextContent[0].Text);
            table.InsertChartAt("H2", basicChart);
            doc.TableCollection.Add(table);
            using (IPackageWriter writer = new OnDiskPackageWriter())
            {
                doc.Save(Path.Combine(AARunMeFirstAndOnce.outPutFolder, "BasicChartWithTitlesetafterwards.ods"), new OpenDocumentTextExporter(writer));
            }
        }
Beispiel #15
0
        public void HTMLExportTest3()
        {
            string   file  = AARunMeFirstAndOnce.inPutFolder + @"simpleCalc.ods";
            FileInfo fInfo = new FileInfo(file);
            //Load a spreadsheet document
            SpreadsheetDocument document = new SpreadsheetDocument();

            using (IPackageReader reader = new OnDiskPackageReader())
            {
                document.Load(file, new OpenDocumentImporter(reader));
                //Save it back again
                document.Save(AARunMeFirstAndOnce.outPutFolder + fInfo.Name + ".html", new OpenDocumentHtmlExporter());
            }
        }
Beispiel #16
0
        private void AddDataToExistingFile <T>(string path, IEnumerable <T> data, bool v) where T : class
        {
            using (SpreadsheetDocument document = SpreadsheetDocument.Open(path, true))
            {
                WorkbookPart workbookPart = document.WorkbookPart;
                IEnumerable <DocumentFormat.OpenXml.Spreadsheet.Sheet> sheets = document.WorkbookPart.Workbook.GetFirstChild <Sheets>().Elements <Sheet>();
                string        relationshipId = sheets.First().Id.Value;
                WorksheetPart worksheetPart  = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId);
                SheetData     sheetdata      = worksheetPart.Worksheet.GetFirstChild <SheetData>();
                SheetData     partSheetData  = GenerateSheetdataForDetails(data, false, sheetdata);

                worksheetPart.Worksheet.Save();
                document.Save();
            }
        }
Beispiel #17
0
 /// <summary>
 /// Sets the extended document properties
 /// </summary>
 /// <param name="document">SpreadSheetDocument reference</param>
 /// <param name="company">Company</param>
 /// <param name="application">Application</param>
 public static void SetExtendedProperties(this SpreadsheetDocument document, Company company, Application application)
 {
     //Add extended Document properties
     if (document.ExtendedFilePropertiesPart == null)
     {
         document.AddExtendedFilePropertiesPart();
     }
     document.ExtendedFilePropertiesPart.Properties = new Properties
     {
         Company     = company ?? new Company(@"izrra.ch"),
         Application = application ?? new Application("Combine.Sdk.Excel")
     };
     //Save all changes
     document.Save();
 }
        /// <summary>
        /// Iterates over all row and cell nodes to check and add (if missing) RowIndex and CellReference attributes.
        /// Those values make it easier to set error style and add comments.
        /// </summary>
        /// <param name="document">File being modified.</param>
        /// <param name="worksheet">Current sheet that is going to be changed.</param>
        public static void StructurateExcelSheetDataXmlAttributes(SpreadsheetDocument document, Worksheet worksheet)
        {
            //Row and Cell nodes are contained within a sheetData node, there is one sheetData node per worksheet.

            SheetData sheetData = worksheet.GetFirstChild <SheetData>();

            bool firstRow        = true;
            int  currentRow      = 0;
            int  currentRowIndex = 0;

            foreach (Row rowItem in sheetData)
            {
                if (rowItem.RowIndex == null)
                {
                    if (firstRow)
                    {
                        currentRow      = 1;
                        currentRowIndex = 1;
                    }
                    else
                    {
                        currentRow++;
                        currentRowIndex++;
                    }
                    rowItem.RowIndex = (uint)currentRowIndex;
                    firstRow         = false;
                }
                else
                {
                    currentRow++;
                    firstRow        = false;
                    currentRowIndex = (int)rowItem.RowIndex.Value;
                    while ((currentRow) < currentRowIndex)
                    {
                        sheetData.InsertBefore(new Row()
                        {
                            RowIndex = (uint)(currentRow)
                        }, rowItem);
                        currentRow++;
                    }
                }
                StructurateCellsInRow(rowItem);
            }
            if (document.FileOpenAccess != FileAccess.Read)
            {
                document.Save();
            }
        }
Beispiel #19
0
        public async static Task ToExcel <TKey, TData>(IEnumerable <IGrouping <TKey, TData> > groupedData, string path)
        {
            using (SpreadsheetDocument document = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook, true))
            {
                DataSet dataSet     = new DataSet();
                uint    uniqueIndex = 1;
                foreach (var data in groupedData)
                {
                    dataSet.Tables.Add(await data.ToDataTable($"{uniqueIndex}_{data.Key}"));
                    uniqueIndex++;
                }
                await CreateExcel(dataSet, document);

                document.Save();
            }
        }
Beispiel #20
0
        /// <summary>
        /// Remove the document protection elements from an XLSX (SpreadsheetDocument) file
        /// </summary>
        /// <param name="filename">XLSX file to remove protection</param>
        public void UnprotectXlsx(string filename)
        {
            using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, true))
            {
                spreadsheetDocument.WorkbookPart.Workbook.RemoveAllChildren <WorkbookProtection>();

                foreach (WorksheetPart worksheetPart in spreadsheetDocument.WorkbookPart.WorksheetParts)
                {
                    worksheetPart.Worksheet.RemoveAllChildren <SheetProtection>();
                }

                spreadsheetDocument.Save();

                spreadsheetDocument.Close();
            }
        }
        public Models.DataTable WriteToTable(Stream stream, IEnumerable <FilterSet> filterSets, bool isEditable, RowStyles rowStyle, string sheetName = "")
        {
            var dataTable = new Models.DataTable();

            using (SpreadsheetDocument document =
                       SpreadsheetDocument.Open(stream, true))
            {
                var result = WriteDataToDocument(document, filterSets, rowStyle == RowStyles.Bordered, sheetName);

                document.Save();
            }

            dataTable.DataRows = null;

            return(dataTable);
        }
        public void NewChartWithAxises()
        {
            SpreadsheetDocument doc = new SpreadsheetDocument();

            using (IPackageReader reader = new OnDiskPackageReader())
            {
                doc.Load(Path.Combine(AARunMeFirstAndOnce.inPutFolder, @"testsheet.ods"), new OpenDocumentImporter(reader));
                Table table = doc.TableCollection[0];
                Chart chart = ChartBuilder.CreateChartByAxises(table, "A1:B2", ChartTypes.line, 2);
                table.InsertChartAt("I2", chart);
                doc.Content.Add(table);
                using (IPackageWriter writer = new OnDiskPackageWriter())
                {
                    doc.Save(Path.Combine(AARunMeFirstAndOnce.outPutFolder, "NewChartWithAxis.ods"), new OpenDocumentTextExporter(writer));
                }
            }
        }
        public void LoadChartModifyTitle()
        {
            SpreadsheetDocument doc = new SpreadsheetDocument();

            using (IPackageReader reader = new OnDiskPackageReader())
            {
                doc.Load(Path.Combine(AARunMeFirstAndOnce.inPutFolder, @"TestChartOne.ods"), new OpenDocumentImporter(reader));
                IContent iContent = doc.EmbedObjects[0];
                ((Chart)iContent).ChartTitle.SetTitle("A New Title");
                ((Chart)iContent).ChartTitle.SvgX = "2cm";
                ((Chart)iContent).ChartTitle.SvgY = "0.5cm";
                using (IPackageWriter writer = new OnDiskPackageWriter())
                {
                    doc.Save(Path.Combine(AARunMeFirstAndOnce.outPutFolder, "TestTitle.ods"), new OpenDocumentTextExporter(writer));
                }
            }
        }
        public void TestLengend()
        {
            SpreadsheetDocument doc = new SpreadsheetDocument();

            using (IPackageReader reader = new OnDiskPackageReader())
            {
                doc.Load(Path.Combine(AARunMeFirstAndOnce.inPutFolder, @"TestChartOne.ods"), new OpenDocumentImporter(reader));
                Chart chart = (Chart)doc.EmbedObjects[0];
                chart.ChartLegend.LegendPosition = "left";
                chart.ChartLegend.SvgX           = "5cm";
                chart.ChartLegend.SvgY           = "2cm";
                using (IPackageWriter writer = new OnDiskPackageWriter())
                {
                    doc.Save(Path.Combine(AARunMeFirstAndOnce.outPutFolder, "TestLegend.ods"), new OpenDocumentTextExporter(writer));
                }
            }
        }
        public void CreateNewChart()

        {
            SpreadsheetDocument doc = new SpreadsheetDocument();

            doc.New();
            Table table = new Table(doc, "tab1", "tab1");

            for (int i = 1; i <= 1; i++)
            {
                for (int j = 1; j <= 6; j++)
                {
                    Cell cell = table.CreateCell();
                    cell.OfficeValueType = "float";
                    Paragraph paragraph = new Paragraph(doc);
                    string    text      = (j + i - 1).ToString();
                    paragraph.TextContent.Add(new SimpleText(doc, text));
                    cell.Content.Add(paragraph);
                    cell.OfficeValueType = "string";
                    cell.OfficeValue     = text;
                    table.InsertCellAt(i, j, cell);
                }
            }

            Chart chart = ChartBuilder.CreateChartByAxisName
                              (table, ChartTypes.bar, "A1:E4", "years", "dollars");

            Assert.AreEqual(7, table.Rows[1].Cells.Count);
            Assert.AreEqual(6, table.Rows[2].Cells.Count);
            Assert.AreEqual(6, table.Rows[3].Cells.Count);
            Assert.AreEqual(6, table.Rows[4].Cells.Count);

            /*Chart chart = new Chart (table,"ch1");
             * chart.ChartType=ChartTypes.bar .ToString () ;
             * chart.XAxisName ="yeer";
             * chart.YAxisName ="dollar";
             * chart.CreateFromCellRange ("A1:E4");
             * chart.EndCellAddress ="tab1.K17";*/
            table.InsertChartAt("G2", chart);

            doc.Content.Add(table);
            using (IPackageWriter writer = new OnDiskPackageWriter())
            {
                doc.Save(Path.Combine(AARunMeFirstAndOnce.outPutFolder, @"NewChartOne.ods"), new OpenDocumentTextExporter(writer));
            }
        }
        public void NewChartWithLegend()
        {
            SpreadsheetDocument doc = new SpreadsheetDocument();

            using (IPackageReader reader = new OnDiskPackageReader())
            {
                doc.Load(Path.Combine(AARunMeFirstAndOnce.inPutFolder, @"testsheet.ods"), new OpenDocumentImporter(reader));
                Table table = doc.TableCollection[0];
                Chart chart = ChartBuilder.CreateChartByLegend(table, "A3:F8", ChartTypes.surface, "left", "0.5", "5",
                                                               "year", "dollars");
                table.InsertChartAt("M2", chart);
                doc.Content.Add(table);
                using (IPackageWriter writer = new OnDiskPackageWriter())
                {
                    doc.Save(Path.Combine(AARunMeFirstAndOnce.outPutFolder, "NewChartWithLegend.ods"), new OpenDocumentTextExporter(writer));
                }
            }
        }
        public void NewChartWithCellRange()
        {
            SpreadsheetDocument doc = new SpreadsheetDocument();

            using (IPackageReader reader = new OnDiskPackageReader())
            {
                doc.Load(Path.Combine(AARunMeFirstAndOnce.inPutFolder, @"testsheet.ods"), new OpenDocumentImporter(reader));
                Table table = doc.TableCollection[0];
                Chart chart = ChartBuilder.CreateChartByCellRange(table, "A4:F8", ChartTypes.bar, null, null,
                                                                  "刘玉花的测试", 3, "bottom", "P14");
                table.InsertChartAt("H2", chart);
                doc.Content.Add(table);
                using (IPackageWriter writer = new OnDiskPackageWriter())
                {
                    doc.Save(Path.Combine(AARunMeFirstAndOnce.outPutFolder, "NewChartWithCellRange.ods"), new OpenDocumentTextExporter(writer));
                }
            }
        }
        public void TestPlotArea()
        {
            SpreadsheetDocument doc = new SpreadsheetDocument();

            using (IPackageReader reader = new OnDiskPackageReader())
            {
                doc.Load(Path.Combine(AARunMeFirstAndOnce.inPutFolder, @"TestChartOne.ods"), new OpenDocumentImporter(reader));
                Chart chart = (Chart)doc.EmbedObjects[0];
                chart.ChartPlotArea.SvgX   = "1.2cm";
                chart.ChartPlotArea.SvgY   = "2.5cm";
                chart.ChartPlotArea.Width  = "5cm";
                chart.ChartPlotArea.Height = "5cm";
                using (IPackageWriter writer = new OnDiskPackageWriter())
                {
                    doc.Save(Path.Combine(AARunMeFirstAndOnce.outPutFolder, "TestPlotArea.ods"), new OpenDocumentTextExporter(writer));
                }
            }
        }
        public void LoadChart()
        {
            SpreadsheetDocument doc = new SpreadsheetDocument();

            using (IPackageReader reader = new OnDiskPackageReader())
            {
                doc.Load(Path.Combine(AARunMeFirstAndOnce.inPutFolder, @"TestChartOne.ods"), new OpenDocumentImporter(reader));
                IContent iContent = doc.EmbedObjects[0];
                ((Chart)iContent).ChartType = ChartTypes.bar.ToString();
                ((Chart)iContent).XAxisName = "XAxis";
                ((Chart)iContent).YAxisName = "YAxis";
                ((Chart)iContent).SvgWidth  = "20cm";
                ((Chart)iContent).SvgHeight = "20cm";
                using (IPackageWriter writer = new OnDiskPackageWriter())
                {
                    doc.Save(Path.Combine(AARunMeFirstAndOnce.outPutFolder, "LoadChart.ods"), new OpenDocumentTextExporter(writer));
                }
            }
        }
Beispiel #30
0
        private void SaveDocument(SpreadsheetDocument document)
        {
            SaveContext  context      = new SaveContext();
            WorkbookPart workbookPart = document.AddWorkbookPart();

            foreach (IdPartPair pair in workbookPart.Parts)
            {
                workbookPart.ChangeIdOfPart(pair.OpenXmlPart, context.RelIdGenerator.GetNext(RelType.Workbook));
            }
            var extendedFilePropertiesPart = document.ExtendedFilePropertiesPart ??
                                             document.AddNewPart <ExtendedFilePropertiesPart>(
                context.RelIdGenerator.GetNext(RelType.Workbook));

            GenerateExtendedFilePropertiesPartContent(extendedFilePropertiesPart);
            CreateWorkbookContent(workbookPart, context);
            WriteCustomProperties(document);
            document.Save();
            document.Close();
        }