zhao
2021-06-04 c7ec496f9e41c2227103b3ef776e4a3f91bce6b2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) Under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for Additional information regarding copyright ownership.
   The ASF licenses this file to You Under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at
 
       http://www.apache.org/licenses/LICENSE-2.0
 
   Unless required by applicable law or agreed to in writing, software
   distributed Under the License is distributed on an "AS Is" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations Under the License.
==================================================================== */
 
namespace HH.WMS.Utils.NPOI.SS.Util
{
 
    using System;
    using System.Text;
    using System.Collections;
    using HH.WMS.Utils.NPOI.SS.Formula;
 
    public class AreaReference
    {
 
        /** The Char (!) that Separates sheet names from cell references */
        private const char SHEET_NAME_DELIMITER = '!';
        /** The Char (:) that Separates the two cell references in a multi-cell area reference */
        private const char CELL_DELIMITER = ':';
        /** The Char (') used to quote sheet names when they contain special Chars */
        private const char SPECIAL_NAME_DELIMITER = '\'';
 
        private CellReference _firstCell;
        private CellReference _lastCell;
        private bool _isSingleCell;
 
        /**
         * Create an area ref from a string representation.  Sheet names containing special Chars should be
         * delimited and escaped as per normal syntax rules for formulas.<br/> 
         * The area reference must be contiguous (i.e. represent a single rectangle, not a Union of rectangles)
         */
        public AreaReference(String reference)
        {
            if (!IsContiguous(reference))
            {
                throw new ArgumentException(
                        "References passed to the AreaReference must be contiguous, " +
                        "use generateContiguous(ref) if you have non-contiguous references");
            }
 
            String[] parts = SeparateAreaRefs(reference);
 
            String part0 = parts[0];
            if (parts.Length == 1)
            {
                // TODO - probably shouldn't initialize area ref when text is really a cell ref
                // Need to fix some named range stuff to get rid of this
                _firstCell = new CellReference(part0);
 
                _lastCell = _firstCell;
                _isSingleCell = true;
                return;
            }
            if (parts.Length != 2)
            {
                throw new ArgumentException("Bad area ref '" + reference + "'");
            }
            String part1 = parts[1];
            if (IsPlainColumn(part0))
            {
                if (!IsPlainColumn(part1))
                {
                    throw new Exception("Bad area ref '" + reference + "'");
                }
                // Special handling for whole-column references
                // Represented internally as x$1 to x$65536
                //  which is the maximum range of rows
 
                bool firstIsAbs = CellReference.IsPartAbsolute(part0);
                bool lastIsAbs = CellReference.IsPartAbsolute(part1);
 
                int col0 = CellReference.ConvertColStringToIndex(part0);
                int col1 = CellReference.ConvertColStringToIndex(part1);
 
                _firstCell = new CellReference(0, col0, true, firstIsAbs);
                _lastCell = new CellReference(0xFFFF, col1, true, lastIsAbs);
                _isSingleCell = false;
                // TODO - whole row refs
            }
            else
            {
                _firstCell = new CellReference(part0);
                _lastCell = new CellReference(part1);
                _isSingleCell = part0.Equals(part1);
            }
        }
 
        private bool IsPlainColumn(String refPart)
        {
            for (int i = refPart.Length - 1; i >= 0; i--)
            {
                int ch = refPart[i];
                if (ch == '$' && i == 0)
                {
                    continue;
                }
                if (ch < 'A' || ch > 'Z')
                {
                    return false;
                }
            }
            return true;
        }
        public static AreaReference GetWholeRow(String start, String end)
        {
            return new AreaReference("$A" + start + ":$IV" + end);
        }
 
        public static AreaReference GetWholeColumn(String start, String end)
        {
            return new AreaReference(start + "$1:" + end + "$65536");
        }
 
 
        /**
         * Creates an area ref from a pair of Cell References.
         */
        public AreaReference(CellReference topLeft, CellReference botRight)
        {
            //_firstCell = topLeft;
            //_lastCell = botRight;
            //_isSingleCell = false;
 
            bool swapRows = topLeft.Row > botRight.Row;
            bool swapCols = topLeft.Col > botRight.Col;
            if (swapRows || swapCols)
            {
                int firstRow;
                int lastRow;
                int firstColumn;
                int lastColumn;
                bool firstRowAbs;
                bool lastRowAbs;
                bool firstColAbs;
                bool lastColAbs;
                if (swapRows)
                {
                    firstRow = botRight.Row;
                    firstRowAbs = botRight.IsRowAbsolute;
                    lastRow = topLeft.Row;
                    lastRowAbs = topLeft.IsRowAbsolute;
                }
                else
                {
                    firstRow = topLeft.Row;
                    firstRowAbs = topLeft.IsRowAbsolute;
                    lastRow = botRight.Row;
                    lastRowAbs = botRight.IsRowAbsolute;
                }
                if (swapCols)
                {
                    firstColumn = botRight.Col;
                    firstColAbs = botRight.IsColAbsolute;
                    lastColumn = topLeft.Col;
                    lastColAbs = topLeft.IsColAbsolute;
                }
                else
                {
                    firstColumn = topLeft.Col;
                    firstColAbs = topLeft.IsColAbsolute;
                    lastColumn = botRight.Col;
                    lastColAbs = botRight.IsColAbsolute;
                }
                _firstCell = new CellReference(firstRow, firstColumn, firstRowAbs, firstColAbs);
                _lastCell = new CellReference(lastRow, lastColumn, lastRowAbs, lastColAbs);
            }
            else
            {
                _firstCell = topLeft;
                _lastCell = botRight;
            }
            _isSingleCell = false;
        }
 
        /**
         * is the reference for a contiguous (i.e.
         *  Unbroken) area, or is it made up of
         *  several different parts?
         * (If it Is, you will need to call
         *  ....
         */
        public static bool IsContiguous(String reference)
        {
            if (reference.IndexOf(',') == -1)
            {
                return true;
            }
            return false;
        }
 
        /**
         * is the reference for a whole-column reference,
         *  such as C:C or D:G ?
         */
        public static bool IsWholeColumnReference(CellReference topLeft, CellReference botRight)
        {
            // These are represented as something like
            //   C$1:C$65535 or D$1:F$0
            // i.e. absolute from 1st row to 0th one
            if (topLeft.Row == 0 && topLeft.IsRowAbsolute &&
                (botRight.Row == -1 || botRight.Row == 65535) && botRight.IsRowAbsolute)
            {
                return true;
            }
            return false;
        }
        public bool IsWholeColumnReference()
        {
            return IsWholeColumnReference(_firstCell, _lastCell);
        }
 
        /**
         * Takes a non-contiguous area reference, and
         *  returns an array of contiguous area references.
         */
        public static AreaReference[] GenerateContiguous(String reference)
        {
            ArrayList refs = new ArrayList();
            String st = reference;
            string[] token = st.Split(',');
            foreach (string t in token)
            {
                refs.Add(
                        new AreaReference(t)
                );
            }
            return (AreaReference[])refs.ToArray(typeof(AreaReference));
        }
 
        /**
         * @return <c>false</c> if this area reference involves more than one cell
         */
        public bool IsSingleCell
        {
            get { return _isSingleCell; }
        }
 
        /**
         * @return the first cell reference which defines this area. Usually this cell is in the upper
         * left corner of the area (but this is not a requirement).
         */
        public CellReference FirstCell
        {
            get { return _firstCell; }
        }
 
        /**
         * Note - if this area reference refers to a single cell, the return value of this method will
         * be identical to that of <c>GetFirstCell()</c>
         * @return the second cell reference which defines this area.  For multi-cell areas, this is 
         * cell diagonally opposite the 'first cell'.  Usually this cell is in the lower right corner 
         * of the area (but this is not a requirement).
         */
        public CellReference LastCell
        {
            get{return _lastCell;}
        }
        /**
         * Returns a reference to every cell covered by this area
         */
        public CellReference[] GetAllReferencedCells()
        {
            // Special case for single cell reference
            if (_isSingleCell)
            {
                return new CellReference[] { _firstCell, };
            }
 
            // Interpolate between the two
            int minRow = Math.Min(_firstCell.Row, _lastCell.Row);
            int maxRow = Math.Max(_firstCell.Row, _lastCell.Row);
            int minCol = Math.Min(_firstCell.Col, _lastCell.Col);
            int maxCol = Math.Max(_firstCell.Col, _lastCell.Col);
            String sheetName = _firstCell.SheetName;
 
            ArrayList refs = new ArrayList();
            for (int row = minRow; row <= maxRow; row++)
            {
                for (int col = minCol; col <= maxCol; col++)
                {
                    CellReference ref1 = new CellReference(sheetName, row, col, _firstCell.IsRowAbsolute, _firstCell.IsColAbsolute);
                    refs.Add(ref1);
                }
            }
            return (CellReference[])refs.ToArray(typeof(CellReference));
        }
 
        /**
         *  Example return values:
         *    <table border="0" cellpAdding="1" cellspacing="0" summary="Example return values">
         *      <tr><th align='left'>Result</th><th align='left'>Comment</th></tr>
         *      <tr><td>A1:A1</td><td>Single cell area reference without sheet</td></tr>
         *      <tr><td>A1:$C$1</td><td>Multi-cell area reference without sheet</td></tr>
         *      <tr><td>Sheet1!A$1:B4</td><td>Standard sheet name</td></tr>
         *      <tr><td>'O''Brien''s Sales'!B5:C6' </td><td>Sheet name with special Chars</td></tr>
         *    </table>
         * @return the text representation of this area reference as it would appear in a formula.
         */
        public String FormatAsString()
        {
                // Special handling for whole-column references
                if (IsWholeColumnReference())
                {
                    return
                        CellReference.ConvertNumToColString(_firstCell.Col)
                        + ":" +
                        CellReference.ConvertNumToColString(_lastCell.Col);
                }
 
                StringBuilder sb = new StringBuilder(32);
                sb.Append(_firstCell.FormatAsString());
                if (!_isSingleCell)
                {
                    sb.Append(CELL_DELIMITER);
                    if (_lastCell.SheetName == null)
                    {
                        sb.Append(_lastCell.FormatAsString());
                    }
                    else
                    {
                        // don't want to include the sheet name twice
                        _lastCell.AppendCellReference(sb);
                    }
                }
                return sb.ToString();
        }
        public override String ToString()
        {
            StringBuilder sb = new StringBuilder(64);
            sb.Append(this.GetType().Name).Append(" [");
            sb.Append(FormatAsString());
            sb.Append("]");
            return sb.ToString();
        }
 
        /**
         * Separates Area refs in two parts and returns them as Separate elements in a String array,
         * each qualified with the sheet name (if present)
         * 
         * @return array with one or two elements. never <c>null</c>
         */
        private static String[] SeparateAreaRefs(String reference)
        {
            // TODO - refactor cell reference parsing logic to one place.
            // Current known incarnations: 
            //   FormulaParser.Name
            //   CellReference.SeparateRefParts() 
            //   AreaReference.SeparateAreaRefs() (here)
            //   SheetNameFormatter.format() (inverse)
 
 
            int len = reference.Length;
            int delimiterPos = -1;
            bool insideDelimitedName = false;
            for (int i = 0; i < len; i++)
            {
                switch (reference[i])
                {
                    case CELL_DELIMITER:
                        if (!insideDelimitedName)
                        {
                            if (delimiterPos >= 0)
                            {
                                throw new ArgumentException("More than one cell delimiter '"
                                        + CELL_DELIMITER + "' appears in area reference '" + reference + "'");
                            }
                            delimiterPos = i;
                        }
                        continue;
                    case SPECIAL_NAME_DELIMITER:
                    // fall through
                        break;
                    default:
                        continue;
                }
                if (!insideDelimitedName)
                {
                    insideDelimitedName = true;
                    continue;
                }
 
                if (i >= len - 1)
                {
                    // reference ends with the delimited name. 
                    // Assume names like: "Sheet1!'A1'" are never legal.
                    throw new ArgumentException("Area reference '" + reference
                            + "' ends with special name delimiter '" + SPECIAL_NAME_DELIMITER + "'");
                }
                if (reference[i + 1] == SPECIAL_NAME_DELIMITER)
                {
                    // two consecutive quotes is the escape sequence for a single one
                    i++; // skip this and keep parsing the special name
                }
                else
                {
                    // this is the end of the delimited name
                    insideDelimitedName = false;
                }
            }
            if (delimiterPos < 0)
            {
                return new String[] { reference, };
            }
 
            String partA = reference.Substring(0, delimiterPos);
            String partB = reference.Substring(delimiterPos + 1);
            if (partB.IndexOf(SHEET_NAME_DELIMITER) >= 0)
            {
                // TODO - are references like "Sheet1!A1:Sheet1:B2" ever valid?  
                // FormulaParser has code to handle that.
 
                throw new Exception("Unexpected " + SHEET_NAME_DELIMITER
                        + " in second cell reference of '" + reference + "'");
            }
 
            int plingPos = partA.LastIndexOf(SHEET_NAME_DELIMITER);
            if (plingPos < 0)
            {
                return new String[] { partA, partB, };
            }
 
            String sheetName = partA.Substring(0, plingPos + 1); // +1 to include delimiter
 
            return new String[] { partA, sheetName + partB, };
        }
    }
 
}