Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix nullable references #168

Merged
merged 10 commits into from
Nov 6, 2023
4 changes: 2 additions & 2 deletions samples/presentation/add_comment/cs/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,14 @@ static SlidePart GetFirstSlide(PresentationDocument? presentationDocument)
string? relId = slideId?.RelationshipId;
if (relId is null)
{
throw new NullReferenceException("The first slide does not contain a relationship ID.");
throw new ArgumentNullException("The first slide does not contain a relationship ID.");
}
// Get the slide part by the relationship ID.
SlidePart? slidePart = part?.GetPartById(relId) as SlidePart;

if (slidePart is null)
{
throw new NullReferenceException("The slide part is null.");
throw new ArgumentNullException("The slide part is null.");
}

return slidePart;
Expand Down
526 changes: 258 additions & 268 deletions samples/presentation/create_by_providing_a_file_name/cs/Program.cs

Large diffs are not rendered by default.

56 changes: 34 additions & 22 deletions samples/presentation/retrieve_the_number_of_slides/cs/Program.cs
Original file line number Diff line number Diff line change
@@ -1,37 +1,49 @@
#nullable disable

using DocumentFormat.OpenXml.Packaging;
using System;
using System.IO.Enumeration;
using System.Linq;

static int RetrieveNumberOfSlides(string fileName,
bool includeHidden = true)
if (args is [ { } fileName, {} includeHidden])
{
RetrieveNumberOfSlides(fileName, includeHidden);
}
else if (args is [{ } fileName2])
{
RetrieveNumberOfSlides(fileName2);
}

static int RetrieveNumberOfSlides(string fileName, string includeHidden = "true")
{
int slidesCount = 0;

using (PresentationDocument doc =
PresentationDocument.Open(fileName, false))
using (PresentationDocument doc = PresentationDocument.Open(fileName, false))
{
// Get the presentation part of the document.
PresentationPart presentationPart = doc.PresentationPart;
if (presentationPart != null)
if (doc is not null && doc.PresentationPart is not null)
{
if (includeHidden)
// Get the presentation part of the document.
PresentationPart presentationPart = doc.PresentationPart;
if (presentationPart is not null)
{
slidesCount = presentationPart.SlideParts.Count();
}
else
{
// Each slide can include a Show property, which if hidden
// will contain the value "0". The Show property may not
// exist, and most likely will not, for non-hidden slides.
var slides = presentationPart.SlideParts.Where(
(s) => (s.Slide != null) &&
((s.Slide.Show == null) || (s.Slide.Show.HasValue &&
s.Slide.Show.Value)));
slidesCount = slides.Count();
if (includeHidden.ToLower() == "true")
{
slidesCount = presentationPart.SlideParts.Count();
}
else
{
// Each slide can include a Show property, which if hidden
// will contain the value "0". The Show property may not
// exist, and most likely will not, for non-hidden slides.
var slides = presentationPart.SlideParts.Where(
(s) => (s.Slide is not null) &&
((s.Slide.Show is null) || (s.Slide.Show.HasValue && s.Slide.Show.Value)));

slidesCount = slides.Count();
}
}
}
}

Console.WriteLine($"Slide Count: {slidesCount}");

return slidesCount;
}
13 changes: 7 additions & 6 deletions samples/spreadsheet/insert_a_new_worksheet/cs/Program.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
#nullable disable

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Linq;

InsertWorksheet(args[0]);

// Given a document name, inserts a new worksheet.
static void InsertWorksheet(string docName)
{
// Open the document for editing.
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
{
WorkbookPart workbookPart = spreadSheet.WorkbookPart ?? spreadSheet.AddWorkbookPart();
// Add a blank WorksheetPart.
WorksheetPart newWorksheetPart = spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
WorksheetPart newWorksheetPart = workbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new Worksheet(new SheetData());

Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = spreadSheet.WorkbookPart.GetIdOfPart(newWorksheetPart);
Sheets sheets = workbookPart.Workbook.GetFirstChild<Sheets>() ?? workbookPart.Workbook.AppendChild(new Sheets());
twsouthwick marked this conversation as resolved.
Show resolved Hide resolved
string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart);

// Get a unique ID for the new worksheet.
uint sheetId = 1;
if (sheets.Elements<Sheet>().Count() > 0)
{
sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
sheetId = (sheets.Elements<Sheet>().Select(s => s.SheetId?.Value).Max() + 1) ?? (uint)sheets.Elements<Sheet>().Count() + 1;
}

// Give the new worksheet a name.
Expand Down
29 changes: 16 additions & 13 deletions samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#nullable disable

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
Expand All @@ -8,6 +6,8 @@
using System.Linq;
using System.Text.RegularExpressions;

MergeTwoCells(args[0], args[1], args[2], args[3]);

// Given a document name, a worksheet name, and the names of two adjacent cells, merges the two cells.
// When two cells are merged, only the content from one cell is preserved:
// the upper-left cell for left-to-right languages or the upper-right cell for right-to-left languages.
Expand All @@ -16,8 +16,8 @@ static void MergeTwoCells(string docName, string sheetName, string cell1Name, st
// Open the document for editing.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(docName, true))
{
Worksheet worksheet = GetWorksheet(document, sheetName);
if (worksheet == null || string.IsNullOrEmpty(cell1Name) || string.IsNullOrEmpty(cell2Name))
Worksheet? worksheet = GetWorksheet(document, sheetName);
if (worksheet is null || string.IsNullOrEmpty(cell1Name) || string.IsNullOrEmpty(cell2Name))
{
return;
}
Expand Down Expand Up @@ -88,7 +88,7 @@ static void CreateSpreadsheetCellIfNotExist(Worksheet worksheet, string cellName
string columnName = GetColumnName(cellName);
uint rowIndex = GetRowIndex(cellName);

IEnumerable<Row> rows = worksheet.Descendants<Row>().Where(r => r.RowIndex.Value == rowIndex);
IEnumerable<Row> rows = worksheet.Descendants<Row>().Where(r => r.RowIndex?.Value == rowIndex);

// If the Worksheet does not contain the specified row, create the specified row.
// Create the specified cell in that row, and insert the row into the Worksheet.
Expand All @@ -98,33 +98,36 @@ static void CreateSpreadsheetCellIfNotExist(Worksheet worksheet, string cellName
Cell cell = new Cell() { CellReference = new StringValue(cellName) };
row.Append(cell);
worksheet.Descendants<SheetData>().First().Append(row);

worksheet.Save();
}
else
{
Row row = rows.First();

IEnumerable<Cell> cells = row.Elements<Cell>().Where(c => c.CellReference.Value == cellName);
IEnumerable<Cell> cells = row.Elements<Cell>().Where(c => c.CellReference?.Value == cellName);

// If the row does not contain the specified cell, create the specified cell.
if (cells.Count() == 0)
{
Cell cell = new Cell() { CellReference = new StringValue(cellName) };
row.Append(cell);

worksheet.Save();
}
}
}

// Given a SpreadsheetDocument and a worksheet name, get the specified worksheet.
static Worksheet GetWorksheet(SpreadsheetDocument document, string worksheetName)
static Worksheet? GetWorksheet(SpreadsheetDocument document, string worksheetName)
{
IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == worksheetName);
WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id);
if (sheets.Count() == 0)
return null;
else
return worksheetPart.Worksheet;
WorkbookPart workbookPart = document.WorkbookPart ?? document.AddWorkbookPart();
IEnumerable<Sheet> sheets = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == worksheetName);

string? id = sheets.First().Id;
WorksheetPart? worksheetPart = id is not null ? (WorksheetPart)workbookPart.GetPartById(id) : null;

return worksheetPart?.Worksheet;
}

// Given a cell name, parses the specified cell to get the column name.
Expand Down
12 changes: 7 additions & 5 deletions samples/spreadsheet/open_for_read_only_access/cs/Program.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
#nullable disable
using DocumentFormat.OpenXml.Packaging;

static void OpenSpreadsheetDocumentReadonly(string filepath)
{
// Open a SpreadsheetDocument based on a filepath.
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filepath, false))
{
// Attempt to add a new WorksheetPart.
// The call to AddNewPart generates an exception because the file is read-only.
WorksheetPart newWorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart<WorksheetPart>();
if (spreadsheetDocument.WorkbookPart is not null)
{
// Attempt to add a new WorksheetPart.
// The call to AddNewPart generates an exception because the file is read-only.
WorksheetPart newWorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart<WorksheetPart>();

// The rest of the code will not be called.
// The rest of the code will not be called.
}
}
}
62 changes: 38 additions & 24 deletions samples/spreadsheet/open_from_a_stream/cs/Program.cs
Original file line number Diff line number Diff line change
@@ -1,39 +1,53 @@
#nullable disable

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.IO;
using System.Linq;

FileStream fileStream = new(args[0], FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
OpenAndAddToSpreadsheetStream(fileStream);

static void OpenAndAddToSpreadsheetStream(Stream stream)
{
// Open a SpreadsheetDocument based on a stream.
SpreadsheetDocument spreadsheetDocument =
SpreadsheetDocument.Open(stream, true);
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(stream, true);

// Add a new worksheet.
WorksheetPart newWorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new Worksheet(new SheetData());
newWorksheetPart.Worksheet.Save();
if (spreadsheetDocument is not null)
{
// Get or create the WorkbookPart
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart ?? spreadsheetDocument.AddWorkbookPart();

Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = spreadsheetDocument.WorkbookPart.GetIdOfPart(newWorksheetPart);
// Add a new worksheet.
WorksheetPart newWorksheetPart = workbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new Worksheet(new SheetData());
newWorksheetPart.Worksheet.Save();

// Get a unique ID for the new worksheet.
uint sheetId = 1;
if (sheets.Elements<Sheet>().Count() > 0)
{
sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
Workbook workbook = workbookPart.Workbook ?? new Workbook();

// Give the new worksheet a name.
string sheetName = "Sheet" + sheetId;
if (workbookPart.Workbook is null)
{
workbookPart.Workbook = workbook;
}

// Append the new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet);
spreadsheetDocument.WorkbookPart.Workbook.Save();
Sheets sheets = workbook.GetFirstChild<Sheets>() ?? workbook.AppendChild(new Sheets());
string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart);

// Dispose the document handle.
spreadsheetDocument.Dispose();
// Get a unique ID for the new worksheet.
uint sheetId = 1;

if (sheets.Elements<Sheet>().Count() > 0)
{
sheetId = (sheets.Elements<Sheet>().Select(s => s.SheetId?.Value).Max() + 1) ?? (uint)sheets.Elements<Sheet>().Count() + 1;
}

// Give the new worksheet a name.
string sheetName = "Sheet" + sheetId;

// Append the new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet);
workbookPart.Workbook.Save();

// Dispose the document handle.
spreadsheetDocument.Dispose();
}
}
Original file line number Diff line number Diff line change
@@ -1,30 +1,33 @@
#nullable disable

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Linq;

ReadExcelFileDOM(args[0]);
ReadExcelFileSAX(args[0]);

// The DOM approach.
// Note that the code below works only for cells that contain numeric values.
//
static void ReadExcelFileDOM(string fileName)
{
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, false))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart ?? spreadsheetDocument.AddWorkbookPart();
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
string text;
string? text;

foreach (Row r in sheetData.Elements<Row>())
{
foreach (Cell c in r.Elements<Cell>())
{
text = c.CellValue.Text;
text = c?.CellValue?.Text;
Console.Write(text + " ");
}
}

Console.WriteLine();
Console.ReadKey();
}
Expand All @@ -35,7 +38,7 @@ static void ReadExcelFileSAX(string fileName)
{
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, false))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart ?? spreadsheetDocument.AddWorkbookPart();
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();

OpenXmlReader reader = OpenXmlReader.Create(worksheetPart);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#nullable disable

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;

GetDefinedNames(args[0]);

static Dictionary<String, String>
GetDefinedNames(String fileName)
{
Expand All @@ -20,14 +20,25 @@ static Dictionary<String, String>
var wbPart = document.WorkbookPart;

// Retrieve a reference to the defined names collection.
DefinedNames definedNames = wbPart.Workbook.DefinedNames;
DefinedNames? definedNames = wbPart?.Workbook?.DefinedNames;

// If there are defined names, add them to the dictionary.
if (definedNames != null)
if (definedNames is not null)
{
foreach (DefinedName dn in definedNames)
returnValue.Add(dn.Name.Value, dn.Text);
{
if (dn?.Name?.Value is not null && dn?.Text is not null)
{
returnValue.Add(dn.Name.Value, dn.Text);
}
}
}
}

foreach (var pair in returnValue)
{
Console.WriteLine("{0} {1}", pair.Key, pair.Value);
}

return returnValue;
}
Loading