private XElement getWorksheet(int worksheetID, PackagePartCollection allParts) { var worksheetName = String.Format("/xl/worksheets/sheet{0}.xml", worksheetID); PackagePart worksheetPart = allParts.Where(x => x.Uri.OriginalString == worksheetName).Single(); return(XElement.Load(XmlReader.Create(worksheetPart.GetStream()))); }
private static List <XDocument> GetContentTypePackageParts( Package filePackage, string contentType) { // Get all of the package parts contained in the package // and then write the URI and content type of each one to the console. PackagePartCollection packageParts = filePackage.GetParts(); var relevantPackageParts = packageParts .Where(pp => pp.ContentType == contentType) .ToList(); foreach (PackagePart packagePart in relevantPackageParts) { Console.WriteLine("Package part URI: {0}", packagePart.Uri); Console.WriteLine("Content type: {0}", packagePart.ContentType); } var results = relevantPackageParts .Select(pp => GetXDocumentFromPackagePart(pp)) .ToList(); return(results); }
/// <summary> /// Run to read file from Open File Dialog as an XLSX file /// </summary> public ISpreadsheet ParseFromFile(string fileName) { using (var xlsxPackage = Package.Open(fileName, FileMode.Open, FileAccess.Read)) { List <Cell> parsedCells = new List <Cell>(); PackagePartCollection allParts = xlsxPackage.GetParts(); PackagePart sharedStringsPart = allParts.Where(x => x.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml").Single(); XElement sharedStringsElement = XElement.Load(XmlReader.Create(sharedStringsPart.GetStream())); Dictionary <int, string> sharedStrings = new Dictionary <int, string>(); parseSharedStrings(sharedStringsElement, sharedStrings); XElement worksheetElement = getWorksheet(1, allParts); IEnumerable <XElement> cells = worksheetElement.Descendants(ExcelNamespaces.Main + "c"); foreach (XElement cell in cells) { string cellPosition = cell.Attribute("r").Value; int index = indexOfNumber(cellPosition); int column = getColumnNumber(cellPosition.Substring(0, index)); int row = Convert.ToInt32(cellPosition.Substring(index, cellPosition.Length - index)); if (cell.HasElements) { if (cell.Attribute("t") != null && cell.Attribute("t").Value == "s") { int valueIndex = Convert.ToInt32(cell.Descendants(ExcelNamespaces.Main + "v").Single().Value); parsedCells.Add(new Cell(column - 1, row - 1, sharedStrings[valueIndex])); } else { string value = cell.Descendants(ExcelNamespaces.Main + "v").Single().Value; parsedCells.Add(new Cell(column - 1, row - 1, value)); } } } return(new Spreadsheet(parsedCells)); } }