|
| 1 | +using System.Globalization; |
| 2 | +using System.Text; |
| 3 | +using DocumentFormat.OpenXml; |
| 4 | +using DocumentFormat.OpenXml.Packaging; |
| 5 | +using DocumentFormat.OpenXml.Spreadsheet; |
| 6 | + |
| 7 | +namespace ManagedCode.FileContext; |
| 8 | + |
| 9 | +internal static class FileContextWorkbookReader |
| 10 | +{ |
| 11 | + private const int AlphabetLength = 26; |
| 12 | + private const int MaximumRows = 1_048_576; |
| 13 | + private const int MaximumColumns = 16_384; |
| 14 | + |
| 15 | + public static FileContextWorkbookInfo Inspect(SpreadsheetDocument document, string path) |
| 16 | + { |
| 17 | + var workbook = RequireWorkbook(document); |
| 18 | + var sheets = workbook.Workbook?.Sheets?.Elements<Sheet>() ?? []; |
| 19 | + return new(path, sheets.Select(sheet => new FileContextWorksheetInfo( |
| 20 | + sheet.Name?.Value ?? string.Empty, |
| 21 | + sheet.State?.InnerText ?? "visible", |
| 22 | + ((WorksheetPart)workbook.GetPartById(sheet.Id!)).Worksheet?.GetFirstChild<SheetDimension>()?.Reference?.Value)).ToArray()); |
| 23 | + } |
| 24 | + |
| 25 | + public static FileContextWorkbookRange Read(SpreadsheetDocument document, string path, string sheetName, |
| 26 | + int startRow, int rowCount, int startColumn, int columnCount, long byteLimit, CancellationToken token) |
| 27 | + { |
| 28 | + ValidateRange(startRow, rowCount, startColumn, columnCount); |
| 29 | + var workbook = RequireWorkbook(document); |
| 30 | + var sheet = workbook.Workbook?.Sheets?.Elements<Sheet>().SingleOrDefault(item => |
| 31 | + string.Equals(item.Name?.Value, sheetName, StringComparison.Ordinal)) |
| 32 | + ?? throw new ArgumentException("The requested worksheet does not exist.", nameof(sheetName)); |
| 33 | + var worksheet = workbook.GetPartById(sheet.Id!) as WorksheetPart |
| 34 | + ?? throw new InvalidDataException("The requested sheet is not a worksheet."); |
| 35 | + var strings = workbook.SharedStringTablePart?.SharedStringTable?.Elements<SharedStringItem>() |
| 36 | + .Select(static item => string.Concat(item.Descendants<Text>().Select(text => text.Text))).ToArray() ?? []; |
| 37 | + var cells = ReadCells(worksheet, strings, startRow, rowCount, startColumn, columnCount, byteLimit, token); |
| 38 | + var range = $"{ColumnName(startColumn)}{startRow}:{ColumnName(startColumn + columnCount - 1)}{startRow + rowCount - 1}"; |
| 39 | + return new(path, sheetName, range, cells); |
| 40 | + } |
| 41 | + |
| 42 | + public static void ValidateRange(int startRow, int rowCount, int startColumn, int columnCount) |
| 43 | + { |
| 44 | + if (startRow < 1 || rowCount < 1 || (long)startRow + rowCount - 1 > MaximumRows) |
| 45 | + { throw new ArgumentOutOfRangeException(nameof(rowCount), "The range must fit Excel's 1048576 rows, starting at one."); } |
| 46 | + if (startColumn < 1 || columnCount < 1 || (long)startColumn + columnCount - 1 > MaximumColumns) |
| 47 | + { throw new ArgumentOutOfRangeException(nameof(columnCount), "The range must fit Excel's 16384 columns, starting at one."); } |
| 48 | + } |
| 49 | + |
| 50 | + private static List<FileContextWorkbookCell> ReadCells(WorksheetPart worksheet, string[] strings, |
| 51 | + int startRow, int rowCount, int startColumn, int columnCount, long byteLimit, CancellationToken token) |
| 52 | + { |
| 53 | + using var reader = OpenXmlReader.Create(worksheet); |
| 54 | + var cells = new List<FileContextWorkbookCell>(); |
| 55 | + long bytes = 0; |
| 56 | + var rowNumber = 0; |
| 57 | + while (reader.Read()) |
| 58 | + { |
| 59 | + token.ThrowIfCancellationRequested(); |
| 60 | + if (reader.ElementType != typeof(Row) || !reader.IsStartElement) { continue; } |
| 61 | + var row = (Row)reader.LoadCurrentElement()!; |
| 62 | + rowNumber = row.RowIndex is null ? rowNumber + 1 : checked((int)row.RowIndex.Value); |
| 63 | + if (rowNumber < startRow || rowNumber >= startRow + rowCount) { continue; } |
| 64 | + var column = 0; |
| 65 | + foreach (var cell in row.Elements<Cell>()) |
| 66 | + { |
| 67 | + token.ThrowIfCancellationRequested(); |
| 68 | + column = cell.CellReference is null ? column + 1 : ReadColumn(cell.CellReference.Value!); |
| 69 | + if (column < startColumn || column >= startColumn + columnCount) { continue; } |
| 70 | + var value = ReadCell(cell, strings, $"{ColumnName(column)}{rowNumber}"); |
| 71 | + bytes += Encoding.UTF8.GetByteCount(value.Value) + Encoding.UTF8.GetByteCount(value.Formula ?? string.Empty) + value.Address.Length + value.Type.Length; |
| 72 | + if (bytes > byteLimit) { throw new IOException("Workbook range exceeds the configured read budget. Request a smaller range."); } |
| 73 | + cells.Add(value); |
| 74 | + } |
| 75 | + } |
| 76 | + return cells; |
| 77 | + } |
| 78 | + |
| 79 | + private static FileContextWorkbookCell ReadCell(Cell cell, string[] strings, string address) |
| 80 | + { |
| 81 | + var type = cell.DataType?.Value; |
| 82 | + var value = cell.CellValue?.Text ?? string.Empty; |
| 83 | + if (type == CellValues.SharedString) |
| 84 | + { |
| 85 | + if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var index) || index < 0 || index >= strings.Length) |
| 86 | + { throw new InvalidDataException("Workbook cell contains an invalid shared-string reference."); } |
| 87 | + value = strings[index]; |
| 88 | + } |
| 89 | + if (type == CellValues.InlineString) |
| 90 | + { value = string.Concat(cell.InlineString?.Descendants<Text>().Select(static text => text.Text) ?? []); } |
| 91 | + var kind = "number"; |
| 92 | + if (type == CellValues.SharedString || type == CellValues.InlineString || type == CellValues.String) { kind = "text"; } |
| 93 | + else if (type == CellValues.Boolean) { kind = "boolean"; } |
| 94 | + else if (type == CellValues.Error) { kind = "error"; } |
| 95 | + else if (type == CellValues.Date) { kind = "date"; } |
| 96 | + else if (value.Length == 0) { kind = "blank"; } |
| 97 | + return new(address, kind, value, cell.CellFormula?.Text); |
| 98 | + } |
| 99 | + |
| 100 | + private static WorkbookPart RequireWorkbook(SpreadsheetDocument document) => |
| 101 | + document.WorkbookPart ?? throw new InvalidDataException("The package has no Excel workbook."); |
| 102 | + |
| 103 | + private static int ReadColumn(string address) |
| 104 | + { |
| 105 | + var result = 0; |
| 106 | + foreach (var character in address.TakeWhile(char.IsAsciiLetter)) |
| 107 | + { result = checked(result * AlphabetLength + char.ToUpperInvariant(character) - 'A' + 1); } |
| 108 | + return result; |
| 109 | + } |
| 110 | + |
| 111 | + private static string ColumnName(int column) |
| 112 | + { |
| 113 | + var result = new StringBuilder(); |
| 114 | + while (column > 0) |
| 115 | + { |
| 116 | + column--; |
| 117 | + result.Insert(0, (char)('A' + column % AlphabetLength)); |
| 118 | + column /= AlphabetLength; |
| 119 | + } |
| 120 | + return result.ToString(); |
| 121 | + } |
| 122 | +} |
0 commit comments