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
/* ====================================================================
   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.Collections.Generic;
    using HH.WMS.Utils.NPOI.SS.UserModel;
 
 
    /**
     * Various utility functions that make working with a cells and rows easier. The various methods
     * that deal with style's allow you to create your CellStyles as you need them. When you apply a
     * style change to a cell, the code will attempt to see if a style already exists that meets your
     * needs. If not, then it will create a new style. This is to prevent creating too many styles.
     * there is an upper limit in Excel on the number of styles that can be supported.
     *
     *@author Eric Pugh epugh@upstate.com
     *@author (secondary) Avinash Kewalramani akewalramani@accelrys.com
     */
    public class CellUtil
    {
 
        public static String ALIGNMENT = "alignment";
        public static String BORDER_BOTTOM = "borderBottom";
        public static String BORDER_LEFT = "borderLeft";
        public static String BORDER_RIGHT = "borderRight";
        public static String BORDER_TOP = "borderTop";
        public static String BOTTOM_BORDER_COLOR = "bottomBorderColor";
        public static String DATA_FORMAT = "dataFormat";
        public static String FILL_BACKGROUND_COLOR = "fillBackgroundColor";
        public static String FILL_FOREGROUND_COLOR = "fillForegroundColor";
        public static String FILL_PATTERN = "fillPattern";
        public static String FONT = "font";
        public static String HIDDEN = "hidden";
        public static String INDENTION = "indention";
        public static String LEFT_BORDER_COLOR = "leftBorderColor";
        public static String LOCKED = "locked";
        public static String RIGHT_BORDER_COLOR = "rightBorderColor";
        public static String ROTATION = "rotation";
        public static String TOP_BORDER_COLOR = "topBorderColor";
        public static String VERTICAL_ALIGNMENT = "verticalAlignment";
        public static String WRAP_TEXT = "wrapText";
 
        private static UnicodeMapping[] unicodeMappings;
 
        private class UnicodeMapping
        {
 
            public String entityName;
            public String resolvedValue;
 
            public UnicodeMapping(String pEntityName, String pResolvedValue)
            {
                entityName = "&" + pEntityName + ";";
                resolvedValue = pResolvedValue;
            }
        }
 
        private CellUtil()
        {
            // no instances of this class
        }
 
        /**
         * Get a row from the spreadsheet, and create it if it doesn't exist.
         *
         *@param rowIndex The 0 based row number
         *@param sheet The sheet that the row is part of.
         *@return The row indicated by the rowCounter
         */
        public static IRow GetRow(int rowIndex, ISheet sheet)
        {
            IRow row = sheet.GetRow(rowIndex);
            if (row == null)
            {
                row = sheet.CreateRow(rowIndex);
            }
            return row;
        }
 
 
        /**
         * Get a specific cell from a row. If the cell doesn't exist, then create it.
         *
         *@param row The row that the cell is part of
         *@param columnIndex The column index that the cell is in.
         *@return The cell indicated by the column.
         */
        public static ICell GetCell(IRow row, int columnIndex)
        {
            ICell cell = row.GetCell(columnIndex);
 
            if (cell == null)
            {
                cell = row.CreateCell(columnIndex);
            }
            return cell;
        }
 
 
        /**
         * Creates a cell, gives it a value, and applies a style if provided
         *
         * @param  row     the row to create the cell in
         * @param  column  the column index to create the cell in
         * @param  value   The value of the cell
         * @param  style   If the style is not null, then set
         * @return         A new Cell
         */
        public static ICell CreateCell(IRow row, int column, String value, ICellStyle style)
        {
            ICell cell = GetCell(row, column);
 
            cell.SetCellValue(cell.Row.Sheet.Workbook.GetCreationHelper()
                    .CreateRichTextString(value));
            if (style != null)
            {
                cell.CellStyle = (style);
            }
            return cell;
        }
 
 
        /**
         * Create a cell, and give it a value.
         *
         *@param  row     the row to create the cell in
         *@param  column  the column index to create the cell in
         *@param  value   The value of the cell
         *@return         A new Cell.
         */
        public static ICell CreateCell(IRow row, int column, String value)
        {
            return CreateCell(row, column, value, null);
        }
 
 
        /**
         * Take a cell, and align it.
         *
         *@param cell the cell to set the alignment for
         *@param workbook The workbook that is being worked with.
         *@param align the column alignment to use.
         *
         * @see CellStyle for alignment options
         */
        public static void SetAlignment(ICell cell, IWorkbook workbook, short align)
        {
            SetCellStyleProperty(cell, workbook, ALIGNMENT, align);
        }
 
        /**
         * Take a cell, and apply a font to it
         *
         *@param cell the cell to set the alignment for
         *@param workbook The workbook that is being worked with.
         *@param font The Font that you want to set...
         */
        public static void SetFont(ICell cell, IWorkbook workbook, IFont font)
        {
            SetCellStyleProperty(cell, workbook, FONT, font.Index);
        }
 
        /**
         * This method attempt to find an already existing CellStyle that matches what you want the
         * style to be. If it does not find the style, then it creates a new one. If it does create a
         * new one, then it applies the propertyName and propertyValue to the style. This is necessary
         * because Excel has an upper limit on the number of Styles that it supports.
         *
         *@param workbook The workbook that is being worked with.
         *@param propertyName The name of the property that is to be changed.
         *@param propertyValue The value of the property that is to be changed.
         *@param cell The cell that needs it's style changes
         */
        public static void SetCellStyleProperty(ICell cell, IWorkbook workbook, String propertyName,
                Object propertyValue)
        {
            ICellStyle originalStyle = cell.CellStyle;
            ICellStyle newStyle = null;
            Dictionary<String, Object> values = GetFormatProperties(originalStyle);
            if (values.ContainsKey(propertyName))
                values[propertyName] = propertyValue;
            else
                values.Add(propertyName, propertyValue);
 
            // index seems like what index the cellstyle is in the list of styles for a workbook.
            // not good to compare on!
            short numberCellStyles = workbook.NumCellStyles;
 
            for (short i = 0; i < numberCellStyles; i++)
            {
                ICellStyle wbStyle = workbook.GetCellStyleAt(i);
 
                Dictionary<String, Object> wbStyleMap = GetFormatProperties(wbStyle);
 
                if (wbStyleMap.Equals(values))
                {
                    newStyle = wbStyle;
                    break;
                }
            }
 
            if (newStyle == null)
            {
                newStyle = workbook.CreateCellStyle();
                SetFormatProperties(newStyle, workbook, values);
            }
 
            cell.CellStyle=(newStyle);
        }
 
        /**
         * Returns a map containing the format properties of the given cell style.
         *
         * @param style cell style
         * @return map of format properties (String -> Object)
         * @see #setFormatProperties(org.apache.poi.ss.usermodel.CellStyle, org.apache.poi.ss.usermodel.Workbook, java.util.Map)
         */
        private static Dictionary<String, Object> GetFormatProperties(ICellStyle style)
        {
            Dictionary<String, Object> properties = new Dictionary<String, Object>();
            PutShort(properties, ALIGNMENT, (short)style.Alignment);
            PutShort(properties, BORDER_BOTTOM, (short)style.BorderBottom);
            PutShort(properties, BORDER_LEFT, (short)style.BorderLeft);
            PutShort(properties, BORDER_RIGHT, (short)style.BorderRight);
            PutShort(properties, BORDER_TOP, (short)style.BorderTop);
            PutShort(properties, BOTTOM_BORDER_COLOR, style.BottomBorderColor);
            PutShort(properties, DATA_FORMAT, style.DataFormat);
            PutShort(properties, FILL_BACKGROUND_COLOR, style.FillBackgroundColor);
            PutShort(properties, FILL_FOREGROUND_COLOR, style.FillForegroundColor);
            PutShort(properties, FILL_PATTERN, (short)style.FillPattern);
            PutShort(properties, FONT, style.FontIndex);
            PutBoolean(properties, HIDDEN, style.IsHidden);
            PutShort(properties, INDENTION, style.Indention);
            PutShort(properties, LEFT_BORDER_COLOR, style.LeftBorderColor);
            PutBoolean(properties, LOCKED, style.IsLocked);
            PutShort(properties, RIGHT_BORDER_COLOR, style.RightBorderColor);
            PutShort(properties, ROTATION, style.Rotation);
            PutShort(properties, TOP_BORDER_COLOR, style.TopBorderColor);
            PutShort(properties, VERTICAL_ALIGNMENT, (short)style.VerticalAlignment);
            PutBoolean(properties, WRAP_TEXT, style.WrapText);
            return properties;
        }
 
        /**
         * Sets the format properties of the given style based on the given map.
         *
         * @param style cell style
         * @param workbook parent workbook
         * @param properties map of format properties (String -> Object)
         * @see #getFormatProperties(CellStyle)
         */
        private static void SetFormatProperties(ICellStyle style, IWorkbook workbook, Dictionary<String, Object> properties)
        {
            style.Alignment=(HorizontalAlignment)(GetShort(properties, ALIGNMENT));
            style.BorderBottom=(BorderStyle)(GetShort(properties, BORDER_BOTTOM));
            style.BorderLeft=(BorderStyle)(GetShort(properties, BORDER_LEFT));
            style.BorderRight=(BorderStyle)(GetShort(properties, BORDER_RIGHT));
            style.BorderTop=(BorderStyle)(GetShort(properties, BORDER_TOP));
            style.BottomBorderColor=(GetShort(properties, BOTTOM_BORDER_COLOR));
            style.DataFormat=(GetShort(properties, DATA_FORMAT));
            style.FillBackgroundColor=(GetShort(properties, FILL_BACKGROUND_COLOR));
            style.FillForegroundColor=(GetShort(properties, FILL_FOREGROUND_COLOR));
            style.FillPattern=(FillPatternType)(GetShort(properties, FILL_PATTERN));
            style.SetFont(workbook.GetFontAt(GetShort(properties, FONT)));
            style.IsHidden=(GetBoolean(properties, HIDDEN));
            style.Indention=(GetShort(properties, INDENTION));
            style.LeftBorderColor=(GetShort(properties, LEFT_BORDER_COLOR));
            style.IsLocked=(GetBoolean(properties, LOCKED));
            style.RightBorderColor=(GetShort(properties, RIGHT_BORDER_COLOR));
            style.Rotation=(GetShort(properties, ROTATION));
            style.TopBorderColor=(GetShort(properties, TOP_BORDER_COLOR));
            style.VerticalAlignment=(VerticalAlignment)(GetShort(properties, VERTICAL_ALIGNMENT));
            style.WrapText=(GetBoolean(properties, WRAP_TEXT));
        }
 
        /**
         * Utility method that returns the named short value form the given map.
         * @return zero if the property does not exist, or is not a {@link Short}.
         *
         * @param properties map of named properties (String -> Object)
         * @param name property name
         * @return property value, or zero
         */
        private static short GetShort(Dictionary<String, Object> properties, String name)
        {
            Object value = properties[name];
            short result = 0;
            if (short.TryParse(value.ToString(), out result))
                return result;
            return 0;
        }
 
        /**
         * Utility method that returns the named boolean value form the given map.
         * @return false if the property does not exist, or is not a {@link Boolean}.
         *
         * @param properties map of properties (String -> Object)
         * @param name property name
         * @return property value, or false
         */
        private static bool GetBoolean(Dictionary<String, Object> properties, String name)
        {
            Object value = properties[name];
            bool result = false;
            if (bool.TryParse(value.ToString(), out result))
                return result;
 
            return false;
        }
 
        /**
         * Utility method that puts the named short value to the given map.
         *
         * @param properties map of properties (String -> Object)
         * @param name property name
         * @param value property value
         */
        private static void PutShort(Dictionary<String, Object> properties, String name, short value)
        {
            if (properties.ContainsKey(name))
                properties[name] = value;
            else
                properties.Add(name, value);
        }
 
        /**
         * Utility method that puts the named boolean value to the given map.
         *
         * @param properties map of properties (String -> Object)
         * @param name property name
         * @param value property value
         */
        private static void PutBoolean(Dictionary<String, Object> properties, String name, bool value)
        {
            if (properties.ContainsKey(name))
                properties[name] = value;
            else
                properties.Add(name, value);
        }
 
        /**
         *  Looks for text in the cell that should be unicode, like an alpha and provides the
         *  unicode version of it.
         *
         *@param  cell  The cell to check for unicode values
         *@return       translated to unicode
         */
        public static ICell TranslateUnicodeValues(ICell cell)
        {
 
            String s = cell.RichStringCellValue.String;
            bool foundUnicode = false;
            String lowerCaseStr = s.ToLower();
 
            for (int i = 0; i < unicodeMappings.Length; i++)
            {
                UnicodeMapping entry = unicodeMappings[i];
                String key = entry.entityName;
                if (lowerCaseStr.IndexOf(key, StringComparison.Ordinal) != -1)
                {
                    s = s.Replace(key, entry.resolvedValue);
                    foundUnicode = true;
                }
            }
            if (foundUnicode)
            {
                cell.SetCellValue(cell.Row.Sheet.Workbook.GetCreationHelper()
                        .CreateRichTextString(s));
            }
            return cell;
        }
 
        static CellUtil()
        {
            unicodeMappings = new UnicodeMapping[] {
            um("alpha",   "\u03B1" ),
            um("beta",    "\u03B2" ),
            um("gamma",   "\u03B3" ),
            um("delta",   "\u03B4" ),
            um("epsilon", "\u03B5" ),
            um("zeta",    "\u03B6" ),
            um("eta",     "\u03B7" ),
            um("theta",   "\u03B8" ),
            um("iota",    "\u03B9" ),
            um("kappa",   "\u03BA" ),
            um("lambda",  "\u03BB" ),
            um("mu",      "\u03BC" ),
            um("nu",      "\u03BD" ),
            um("xi",      "\u03BE" ),
            um("omicron", "\u03BF" ),
        };
        }
 
        private static UnicodeMapping um(String entityName, String resolvedValue)
        {
            return new UnicodeMapping(entityName, resolvedValue);
        }
    }
}