styles.go 108.0 KB
Newer Older
xurime's avatar
xurime 已提交
1
// Copyright 2016 - 2023 The excelize Authors. All rights reserved. Use of
xurime's avatar
xurime 已提交
2 3 4
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
5 6 7 8 9
// Package excelize providing a set of functions that allow you to write to and
// read from XLAM / XLSM / XLSX / XLTM / XLTX files. Supports reading and
// writing spreadsheet documents generated by Microsoft Excel™ 2007 and later.
// Supports complex components by high compatibility, and provided streaming
// API for generating or reading data from a worksheet with huge amounts of
xurime's avatar
xurime 已提交
10
// data. This library needs Go version 1.16 or later.
xurime's avatar
xurime 已提交
11

12 13 14
package excelize

import (
15
	"bytes"
16
	"encoding/xml"
17
	"fmt"
18
	"io"
19
	"math"
20
	"reflect"
21
	"sort"
22 23 24 25
	"strconv"
	"strings"
)

xurime's avatar
xurime 已提交
26
// stylesReader provides a function to get the pointer to the structure after
27
// deserialization of xl/styles.xml.
28
func (f *File) stylesReader() (*xlsxStyleSheet, error) {
29
	if f.Styles == nil {
30
		f.Styles = new(xlsxStyleSheet)
31
		if err := f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(defaultXMLPathStyles)))).
32
			Decode(f.Styles); err != nil && err != io.EOF {
33
			return f.Styles, err
34
		}
35
	}
36
	return f.Styles, nil
37 38
}

xurime's avatar
xurime 已提交
39
// styleSheetWriter provides a function to save xl/styles.xml after serialize
40 41 42 43
// structure.
func (f *File) styleSheetWriter() {
	if f.Styles != nil {
		output, _ := xml.Marshal(f.Styles)
44
		f.saveFileList(defaultXMLPathStyles, f.replaceNameSpaceBytes(defaultXMLPathStyles, output))
45 46 47
	}
}

48 49 50
// themeWriter provides a function to save xl/theme/theme1.xml after serialize
// structure.
func (f *File) themeWriter() {
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
	newColor := func(c *decodeCTColor) xlsxCTColor {
		return xlsxCTColor{
			ScrgbClr:  c.ScrgbClr,
			SrgbClr:   c.SrgbClr,
			HslClr:    c.HslClr,
			SysClr:    c.SysClr,
			SchemeClr: c.SchemeClr,
			PrstClr:   c.PrstClr,
		}
	}
	newFontScheme := func(c *decodeFontCollection) xlsxFontCollection {
		return xlsxFontCollection{
			Latin:  c.Latin,
			Ea:     c.Ea,
			Cs:     c.Cs,
			Font:   c.Font,
			ExtLst: c.ExtLst,
		}
	}
70
	if f.Theme != nil {
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
		output, _ := xml.Marshal(xlsxTheme{
			XMLNSa: NameSpaceDrawingML.Value,
			XMLNSr: SourceRelationship.Value,
			Name:   f.Theme.Name,
			ThemeElements: xlsxBaseStyles{
				ClrScheme: xlsxColorScheme{
					Name:     f.Theme.ThemeElements.ClrScheme.Name,
					Dk1:      newColor(&f.Theme.ThemeElements.ClrScheme.Dk1),
					Lt1:      newColor(&f.Theme.ThemeElements.ClrScheme.Lt1),
					Dk2:      newColor(&f.Theme.ThemeElements.ClrScheme.Dk2),
					Lt2:      newColor(&f.Theme.ThemeElements.ClrScheme.Lt2),
					Accent1:  newColor(&f.Theme.ThemeElements.ClrScheme.Accent1),
					Accent2:  newColor(&f.Theme.ThemeElements.ClrScheme.Accent2),
					Accent3:  newColor(&f.Theme.ThemeElements.ClrScheme.Accent3),
					Accent4:  newColor(&f.Theme.ThemeElements.ClrScheme.Accent4),
					Accent5:  newColor(&f.Theme.ThemeElements.ClrScheme.Accent5),
					Accent6:  newColor(&f.Theme.ThemeElements.ClrScheme.Accent6),
					Hlink:    newColor(&f.Theme.ThemeElements.ClrScheme.Hlink),
					FolHlink: newColor(&f.Theme.ThemeElements.ClrScheme.FolHlink),
					ExtLst:   f.Theme.ThemeElements.ClrScheme.ExtLst,
				},
				FontScheme: xlsxFontScheme{
					Name:      f.Theme.ThemeElements.FontScheme.Name,
					MajorFont: newFontScheme(&f.Theme.ThemeElements.FontScheme.MajorFont),
					MinorFont: newFontScheme(&f.Theme.ThemeElements.FontScheme.MinorFont),
					ExtLst:    f.Theme.ThemeElements.FontScheme.ExtLst,
				},
				FmtScheme: xlsxStyleMatrix{
					Name:           f.Theme.ThemeElements.FmtScheme.Name,
					FillStyleLst:   f.Theme.ThemeElements.FmtScheme.FillStyleLst,
					LnStyleLst:     f.Theme.ThemeElements.FmtScheme.LnStyleLst,
					EffectStyleLst: f.Theme.ThemeElements.FmtScheme.EffectStyleLst,
					BgFillStyleLst: f.Theme.ThemeElements.FmtScheme.BgFillStyleLst,
				},
				ExtLst: f.Theme.ThemeElements.ExtLst,
			},
			ObjectDefaults:    f.Theme.ObjectDefaults,
			ExtraClrSchemeLst: f.Theme.ExtraClrSchemeLst,
			CustClrLst:        f.Theme.CustClrLst,
			ExtLst:            f.Theme.ExtLst,
		})
112 113 114 115
		f.saveFileList(defaultXMLPathTheme, f.replaceNameSpaceBytes(defaultXMLPathTheme, output))
	}
}

xurime's avatar
xurime 已提交
116 117 118 119 120
// sharedStringsWriter provides a function to save xl/sharedStrings.xml after
// serialize structure.
func (f *File) sharedStringsWriter() {
	if f.SharedStrings != nil {
		output, _ := xml.Marshal(f.SharedStrings)
121
		f.saveFileList(defaultXMLPathSharedStrings, f.replaceNameSpaceBytes(defaultXMLPathSharedStrings, output))
xurime's avatar
xurime 已提交
122 123 124
	}
}

xurime's avatar
xurime 已提交
125
// parseFormatStyleSet provides a function to parse the format settings of the
126
// cells and conditional formats.
127
func parseFormatStyleSet(style *Style) (*Style, error) {
128
	var err error
129 130 131
	if style.Font != nil {
		if len(style.Font.Family) > MaxFontFamilyLength {
			return style, ErrFontLength
132
		}
133 134
		if style.Font.Size > MaxFontSize {
			return style, ErrFontSize
135 136
		}
	}
137
	if style.CustomNumFmt != nil && len(*style.CustomNumFmt) == 0 {
xurime's avatar
xurime 已提交
138 139
		err = ErrCustomNumFmt
	}
140
	return style, err
141 142
}

143 144 145 146 147
// NewStyle provides a function to create the style for cells by a given style
// options, and returns style index. The same style index can not be used
// across different workbook. This function is concurrency safe. Note that
// the 'Font.Color' field uses an RGB color represented in 'RRGGBB' hexadecimal
// notation.
148
//
149 150 151 152 153 154 155 156 157 158 159 160 161 162
// The following table shows the border types used in 'Border.Type' supported by
// excelize:
//
//	 Type         | Description
//	--------------+------------------
//	 left         | Left border
//	 top          | Top border
//	 right        | Right border
//	 bottom       | Bottom border
//	 diagonalDown | Diagonal down border
//	 diagonalUp   | Diagonal up border
//
// The following table shows the border styles used in 'Border.Style' supported
// by excelize index number:
163
//
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
//	 Index | Name          | Weight | Style
//	-------+---------------+--------+-------------
//	 0     | None          | 0      |
//	 1     | Continuous    | 1      | -----------
//	 2     | Continuous    | 2      | -----------
//	 3     | Dash          | 1      | - - - - - -
//	 4     | Dot           | 1      | . . . . . .
//	 5     | Continuous    | 3      | -----------
//	 6     | Double        | 3      | ===========
//	 7     | Continuous    | 0      | -----------
//	 8     | Dash          | 2      | - - - - - -
//	 9     | Dash Dot      | 1      | - . - . - .
//	 10    | Dash Dot      | 2      | - . - . - .
//	 11    | Dash Dot Dot  | 1      | - . . - . .
//	 12    | Dash Dot Dot  | 2      | - . . - . .
//	 13    | SlantDash Dot | 2      | / - . / - .
180
//
181 182
// The following table shows the border styles used in 'Border.Style' in the
// order shown in the Excel dialog:
183
//
184 185 186 187 188 189 190 191 192
//	 Index | Style       | Index | Style
//	-------+-------------+-------+-------------
//	 0     | None        | 12    | - . . - . .
//	 7     | ----------- | 13    | / - . / - .
//	 4     | . . . . . . | 10    | - . - . - .
//	 11    | - . . - . . | 8     | - - - - - -
//	 9     | - . - . - . | 2     | -----------
//	 3     | - - - - - - | 5     | -----------
//	 1     | ----------- | 6     | ===========
193
//
194 195
// The following table shows the shading styles used in 'Fill.Shading' supported
// by excelize index number:
196
//
197 198
//	 Index | Style           | Index | Style
//	-------+-----------------+-------+-----------------
199 200 201
//	 0-2   | Horizontal      | 9-11  | Diagonal down
//	 3-5   | Vertical        | 12-15 | From corner
//	 6-8   | Diagonal Up     | 16    | From center
202
//
203 204
// The following table shows the pattern styles used in 'Fill.Pattern' supported
// by excelize index number:
205
//
206 207 208 209 210 211 212 213 214 215 216 217
//	 Index | Style           | Index | Style
//	-------+-----------------+-------+-----------------
//	 0     | None            | 10    | darkTrellis
//	 1     | solid           | 11    | lightHorizontal
//	 2     | mediumGray      | 12    | lightVertical
//	 3     | darkGray        | 13    | lightDown
//	 4     | lightGray       | 14    | lightUp
//	 5     | darkHorizontal  | 15    | lightGrid
//	 6     | darkVertical    | 16    | lightTrellis
//	 7     | darkDown        | 17    | gray125
//	 8     | darkUp          | 18    | gray0625
//	 9     | darkGrid        |       |
218
//
219 220 221 222 223 224 225 226 227 228 229 230
// The 'Alignment.Indent' is an integer value, where an increment of 1
// represents 3 spaces. Indicates the number of spaces (of the normal style
// font) of indentation for text in a cell. The number of spaces to indent is
// calculated as following:
//
//	Number of spaces to indent = indent value * 3
//
// For example, an indent value of 1 means that the text begins 3 space widths
// (of the normal style font) from the edge of the cell. Note: The width of one
// space character is defined by the font. Only left, right, and distributed
// horizontal alignments are supported.
//
231 232
// The following table shows the type of cells' horizontal alignment used
// in 'Alignment.Horizontal':
233
//
234 235 236 237 238 239 240 241 242
//	 Style
//	------------------
//	 left
//	 center
//	 right
//	 fill
//	 justify
//	 centerContinuous
//	 distributed
243
//
244 245
// The following table shows the type of cells' vertical alignment used in
// 'Alignment.Vertical':
246
//
247 248 249 250 251 252
//	 Style
//	------------------
//	 top
//	 center
//	 justify
//	 distributed
253
//
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
// The 'Alignment.ReadingOrder' is an uint64 value indicating whether the
// reading order of the cell is left-to-right, right-to-left, or context
// dependent. the valid value of this field was:
//
//	 Value | Description
//	-------+----------------------------------------------------
//	 0     | Context Dependent - reading order is determined by scanning the
//	       | text for the first non-whitespace character: if it is a strong
//	       | right-to-left character, the reading order is right-to-left;
//	       | otherwise, the reading order left-to-right.
//	 1     | Left-to-Right: reading order is left-to-right in the cell, as in
//	       | English.
//	 2     | Right-to-Left: reading order is right-to-left in the cell, as in
//	       | Hebrew.
//
// The 'Alignment.RelativeIndent' is an integer value to indicate the additional
// number of spaces of indentation to adjust for text in a cell.
//
272 273
// The following table shows the type of font underline style used in
// 'Font.Underline':
274
//
275 276
//	 Style
//	------------------
277
//	 none
278 279
//	 single
//	 double
280
//
281
// Excel's built-in all languages formats are shown in the following table:
xurime's avatar
xurime 已提交
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
//	 Index | Format String
//	-------+----------------------------------------------------
//	 0     | General
//	 1     | 0
//	 2     | 0.00
//	 3     | #,##0
//	 4     | #,##0.00
//	 5     | ($#,##0_);($#,##0)
//	 6     | ($#,##0_);[Red]($#,##0)
//	 7     | ($#,##0.00_);($#,##0.00)
//	 8     | ($#,##0.00_);[Red]($#,##0.00)
//	 9     | 0%
//	 10    | 0.00%
//	 11    | 0.00E+00
//	 12    | # ?/?
//	 13    | # ??/??
//	 14    | m/d/yy
//	 15    | d-mmm-yy
//	 16    | d-mmm
//	 17    | mmm-yy
//	 18    | h:mm AM/PM
//	 19    | h:mm:ss AM/PM
//	 20    | h:mm
//	 21    | h:mm:ss
//	 22    | m/d/yy h:mm
//	 ...   | ...
//	 37    | (#,##0_);(#,##0)
//	 38    | (#,##0_);[Red](#,##0)
//	 39    | (#,##0.00_);(#,##0.00)
//	 40    | (#,##0.00_);[Red](#,##0.00)
//	 41    | _(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)
//	 42    | _($* #,##0_);_($* (#,##0);_($* "-"_);_(@_)
//	 43    | _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)
//	 44    | _($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)
//	 45    | mm:ss
//	 46    | [h]:mm:ss
//	 47    | mm:ss.0
//	 48    | ##0.0E+0
//	 49    | @
322
//
323 324
// Number format code in zh-tw language:
//
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
//	 Index | Symbol
//	-------+-------------------------------------------
//	 27    | [$-404]e/m/d
//	 28    | [$-404]e"年"m"月"d"日"
//	 29    | [$-404]e"年"m"月"d"日"
//	 30    | m/d/yy
//	 31    | yyyy"年"m"月"d"日"
//	 32    | hh"時"mm"分"
//	 33    | hh"時"mm"分"ss"秒"
//	 34    | 上午/下午 hh"時"mm"分"
//	 35    | 上午/下午 hh"時"mm"分"ss"秒"
//	 36    | [$-404]e/m/d
//	 50    | [$-404]e/m/d
//	 51    | [$-404]e"年"m"月"d"日"
//	 52    | 上午/下午 hh"時"mm"分"
//	 53    | 上午/下午 hh"時"mm"分"ss"秒"
//	 54    | [$-404]e"年"m"月"d"日"
//	 55    | 上午/下午 hh"時"mm"分"
//	 56    | 上午/下午 hh"時"mm"分"ss"秒"
//	 57    | [$-404]e/m/d
//	 58    | [$-404]e"年"m"月"d"日"
346 347 348
//
// Number format code in zh-cn language:
//
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
//	 Index | Symbol
//	-------+-------------------------------------------
//	 27    | yyyy"年"m"月"
//	 28    | m"月"d"日"
//	 29    | m"月"d"日"
//	 30    | m-d-yy
//	 31    | yyyy"年"m"月"d"日"
//	 32    | h"时"mm"分"
//	 33    | h"时"mm"分"ss"秒"
//	 34    | 上午/下午 h"时"mm"分"
//	 35    | 上午/下午 h"时"mm"分"ss"秒
//	 36    | yyyy"年"m"月
//	 50    | yyyy"年"m"月
//	 51    | m"月"d"日
//	 52    | yyyy"年"m"月
//	 53    | m"月"d"日
//	 54    | m"月"d"日
//	 55    | 上午/下午 h"时"mm"分
//	 56    | 上午/下午 h"时"mm"分"ss"秒
//	 57    | yyyy"年"m"月
//	 58    | m"月"d"日"
370 371 372
//
// Number format code in ja-jp language:
//
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
//	 Index | Symbol
//	-------+-------------------------------------------
//	 27    | [$-411]ge.m.d
//	 28    | [$-411]ggge"年"m"月"d"日
//	 29    | [$-411]ggge"年"m"月"d"日
//	 30    | m/d/y
//	 31    | yyyy"年"m"月"d"日
//	 32    | h"時"mm"分
//	 33    | h"時"mm"分"ss"秒
//	 34    | yyyy"年"m"月
//	 35    | m"月"d"日
//	 36    | [$-411]ge.m.d
//	 50    | [$-411]ge.m.d
//	 51    | [$-411]ggge"年"m"月"d"日
//	 52    | yyyy"年"m"月
//	 53    | m"月"d"日
//	 54    | [$-411]ggge"年"m"月"d"日
//	 55    | yyyy"年"m"月
//	 56    | m"月"d"日
//	 57    | [$-411]ge.m.d
//	 58    | [$-411]ggge"年"m"月"d"日"
394
//
xurime's avatar
xurime 已提交
395
// Number format code in ko-kr language:
396
//
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
//	 Index | Symbol
//	-------+-------------------------------------------
//	 27    | yyyy"年" mm"月" dd"日
//	 28    | mm-d
//	 29    | mm-d
//	 30    | mm-dd-y
//	 31    | yyyy"년" mm"월" dd"일
//	 32    | h"시" mm"분
//	 33    | h"시" mm"분" ss"초
//	 34    | yyyy-mm-d
//	 35    | yyyy-mm-d
//	 36    | yyyy"年" mm"月" dd"日
//	 50    | yyyy"年" mm"月" dd"日
//	 51    | mm-d
//	 52    | yyyy-mm-d
//	 53    | yyyy-mm-d
//	 54    | mm-d
//	 55    | yyyy-mm-d
//	 56    | yyyy-mm-d
//	 57    | yyyy"年" mm"月" dd"日
//	 58    | mm-dd
418
//
xurime's avatar
xurime 已提交
419
// Number format code in th-th language:
420
//
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
//	 Index | Symbol
//	-------+-------------------------------------------
//	 59    | t
//	 60    | t0.0
//	 61    | t#,##
//	 62    | t#,##0.0
//	 67    | t0
//	 68    | t0.00
//	 69    | t# ?/
//	 70    | t# ??/?
//	 71    | ว/ด/ปปป
//	 72    | ว-ดดด-ป
//	 73    | ว-ดด
//	 74    | ดดด-ป
//	 75    | ช:น
//	 76    | ช:นน:ท
//	 77    | ว/ด/ปปปป ช:น
//	 78    | นน:ท
//	 79    | [ช]:นน:ท
//	 80    | นน:ทท.
//	 81    | d/m/bb
442
//
443 444 445 446 447
// Excelize built-in currency formats are shown in the following table, only
// support these types in the following table (Index number is used only for
// markup and is not used inside an Excel file and you can't get formatted value
// by the function GetCellValue) currently:
//
448 449
//	 Index | Symbol
//	-------+---------------------------------------------------------------
450 451
//	 164   | ¥
//	 165   | $ English (United States)
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
//	 166   | $ Cherokee (United States)
//	 167   | $ Chinese (Singapore)
//	 168   | $ Chinese (Taiwan)
//	 169   | $ English (Australia)
//	 170   | $ English (Belize)
//	 171   | $ English (Canada)
//	 172   | $ English (Jamaica)
//	 173   | $ English (New Zealand)
//	 174   | $ English (Singapore)
//	 175   | $ English (Trinidad & Tobago)
//	 176   | $ English (U.S. Virgin Islands)
//	 177   | $ English (United States)
//	 178   | $ French (Canada)
//	 179   | $ Hawaiian (United States)
//	 180   | $ Malay (Brunei)
//	 181   | $ Quechua (Ecuador)
//	 182   | $ Spanish (Chile)
//	 183   | $ Spanish (Colombia)
//	 184   | $ Spanish (Ecuador)
//	 185   | $ Spanish (El Salvador)
//	 186   | $ Spanish (Mexico)
//	 187   | $ Spanish (Puerto Rico)
//	 188   | $ Spanish (United States)
//	 189   | $ Spanish (Uruguay)
//	 190   | £ English (United Kingdom)
//	 191   | £ Scottish Gaelic (United Kingdom)
//	 192   | £ Welsh (United Kindom)
//	 193   | ¥ Chinese (China)
//	 194   | ¥ Japanese (Japan)
//	 195   | ¥ Sichuan Yi (China)
//	 196   | ¥ Tibetan (China)
//	 197   | ¥ Uyghur (China)
//	 198   | ֏ Armenian (Armenia)
//	 199   | ؋ Pashto (Afghanistan)
//	 200   | ؋ Persian (Afghanistan)
//	 201   | ৳ Bengali (Bangladesh)
//	 202   | ៛ Khmer (Cambodia)
//	 203   | ₡ Spanish (Costa Rica)
//	 204   | ₦ Hausa (Nigeria)
//	 205   | ₦ Igbo (Nigeria)
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
//	 206   | ₩ Korean (South Korea)
//	 207   | ₪ Hebrew (Israel)
//	 208   | ₫ Vietnamese (Vietnam)
//	 209   | € Basque (Spain)
//	 210   | € Breton (France)
//	 211   | € Catalan (Spain)
//	 212   | € Corsican (France)
//	 213   | € Dutch (Belgium)
//	 214   | € Dutch (Netherlands)
//	 215   | € English (Ireland)
//	 216   | € Estonian (Estonia)
//	 217   | € Euro (€ 123)
//	 218   | € Euro (123 €)
//	 219   | € Finnish (Finland)
//	 220   | € French (Belgium)
//	 221   | € French (France)
//	 222   | € French (Luxembourg)
//	 223   | € French (Monaco)
//	 224   | € French (Réunion)
//	 225   | € Galician (Spain)
//	 226   | € German (Austria)
//	 227   | € German (German)
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
//	 228   | € German (Luxembourg)
//	 229   | € Greek (Greece)
//	 230   | € Inari Sami (Finland)
//	 231   | € Irish (Ireland)
//	 232   | € Italian (Italy)
//	 233   | € Latin (Italy)
//	 234   | € Latin, Serbian (Montenegro)
//	 235   | € Larvian (Latvia)
//	 236   | € Lithuanian (Lithuania)
//	 237   | € Lower Sorbian (Germany)
//	 238   | € Luxembourgish (Luxembourg)
//	 239   | € Maltese (Malta)
//	 240   | € Northern Sami (Finland)
//	 241   | € Occitan (France)
//	 242   | € Portuguese (Portugal)
//	 243   | € Serbian (Montenegro)
//	 244   | € Skolt Sami (Finland)
//	 245   | € Slovak (Slovakia)
//	 246   | € Slovenian (Slovenia)
//	 247   | € Spanish (Spain)
//	 248   | € Swedish (Finland)
//	 249   | € Swiss German (France)
//	 250   | € Upper Sorbian (Germany)
//	 251   | € Western Frisian (Netherlands)
//	 252   | ₭ Lao (Laos)
//	 253   | ₮ Mongolian (Mongolia)
//	 254   | ₮ Mongolian, Mongolian (Mongolia)
//	 255   | ₱ English (Philippines)
//	 256   | ₱ Filipino (Philippines)
//	 257   | ₴ Ukrainian (Ukraine)
//	 258   | ₸ Kazakh (Kazakhstan)
//	 259   | ₹ Arabic, Kashmiri (India)
//	 260   | ₹ English (India)
//	 261   | ₹ Gujarati (India)
//	 262   | ₹ Hindi (India)
//	 263   | ₹ Kannada (India)
//	 264   | ₹ Kashmiri (India)
//	 265   | ₹ Konkani (India)
//	 266   | ₹ Manipuri (India)
//	 267   | ₹ Marathi (India)
//	 268   | ₹ Nepali (India)
//	 269   | ₹ Oriya (India)
//	 270   | ₹ Punjabi (India)
//	 271   | ₹ Sanskrit (India)
//	 272   | ₹ Sindhi (India)
//	 273   | ₹ Tamil (India)
//	 274   | ₹ Urdu (India)
//	 275   | ₺ Turkish (Turkey)
//	 276   | ₼ Azerbaijani (Azerbaijan)
//	 277   | ₼ Cyrillic, Azerbaijani (Azerbaijan)
//	 278   | ₽ Russian (Russia)
//	 279   | ₽ Sakha (Russia)
//	 280   | ₾ Georgian (Georgia)
//	 281   | B/. Spanish (Panama)
//	 282   | Br Oromo (Ethiopia)
//	 283   | Br Somali (Ethiopia)
//	 284   | Br Tigrinya (Ethiopia)
//	 285   | Bs Quechua (Bolivia)
//	 286   | Bs Spanish (Bolivia)
//	 287   | BS. Spanish (Venezuela)
//	 288   | BWP Tswana (Botswana)
//	 289   | C$ Spanish (Nicaragua)
//	 290   | CA$ Latin, Inuktitut (Canada)
//	 291   | CA$ Mohawk (Canada)
//	 292   | CA$ Unified Canadian Aboriginal Syllabics, Inuktitut (Canada)
//	 293   | CFA French (Mali)
//	 294   | CFA French (Senegal)
//	 295   | CFA Fulah (Senegal)
//	 296   | CFA Wolof (Senegal)
//	 297   | CHF French (Switzerland)
//	 298   | CHF German (Liechtenstein)
//	 299   | CHF German (Switzerland)
//	 300   | CHF Italian (Switzerland)
//	 301   | CHF Romansh (Switzerland)
//	 302   | CLP Mapuche (Chile)
//	 303   | CN¥ Mongolian, Mongolian (China)
//	 304   | DZD Central Atlas Tamazight (Algeria)
//	 305   | FCFA French (Cameroon)
//	 306   | Ft Hungarian (Hungary)
//	 307   | G French (Haiti)
//	 308   | Gs. Spanish (Paraguay)
//	 309   | GTQ K'iche' (Guatemala)
//	 310   | HK$ Chinese (Hong Kong (China))
//	 311   | HK$ English (Hong Kong (China))
//	 312   | HRK Croatian (Croatia)
//	 313   | IDR English (Indonesia)
//	 314   | IQD Arbic, Central Kurdish (Iraq)
//	 315   | ISK Icelandic (Iceland)
//	 316   | K Burmese (Myanmar (Burma))
//	 317   | Kč Czech (Czech Republic)
//	 318   | KM Bosnian (Bosnia & Herzegovina)
//	 319   | KM Croatian (Bosnia & Herzegovina)
//	 320   | KM Latin, Serbian (Bosnia & Herzegovina)
//	 321   | kr Faroese (Faroe Islands)
//	 322   | kr Northern Sami (Norway)
//	 323   | kr Northern Sami (Sweden)
//	 324   | kr Norwegian Bokmål (Norway)
//	 325   | kr Norwegian Nynorsk (Norway)
//	 326   | kr Swedish (Sweden)
//	 327   | kr. Danish (Denmark)
//	 328   | kr. Kalaallisut (Greenland)
//	 329   | Ksh Swahili (kenya)
//	 330   | L Romanian (Moldova)
//	 331   | L Russian (Moldova)
//	 332   | L Spanish (Honduras)
//	 333   | Lekë Albanian (Albania)
//	 334   | MAD Arabic, Central Atlas Tamazight (Morocco)
//	 335   | MAD French (Morocco)
//	 336   | MAD Tifinagh, Central Atlas Tamazight (Morocco)
//	 337   | MOP$ Chinese (Macau (China))
//	 338   | MVR Divehi (Maldives)
//	 339   | Nfk Tigrinya (Eritrea)
//	 340   | NGN Bini (Nigeria)
//	 341   | NGN Fulah (Nigeria)
//	 342   | NGN Ibibio (Nigeria)
//	 343   | NGN Kanuri (Nigeria)
//	 344   | NOK Lule Sami (Norway)
//	 345   | NOK Southern Sami (Norway)
//	 346   | NZ$ Maori (New Zealand)
//	 347   | PKR Sindhi (Pakistan)
//	 348   | PYG Guarani (Paraguay)
//	 349   | Q Spanish (Guatemala)
//	 350   | R Afrikaans (South Africa)
//	 351   | R English (South Africa)
//	 352   | R Zulu (South Africa)
//	 353   | R$ Portuguese (Brazil)
//	 354   | RD$ Spanish (Dominican Republic)
//	 355   | RF Kinyarwanda (Rwanda)
//	 356   | RM English (Malaysia)
//	 357   | RM Malay (Malaysia)
//	 358   | RON Romanian (Romania)
//	 359   | Rp Indonesoan (Indonesia)
//	 360   | Rs Urdu (Pakistan)
//	 361   | Rs. Tamil (Sri Lanka)
//	 362   | RSD Latin, Serbian (Serbia)
//	 363   | RSD Serbian (Serbia)
//	 364   | RUB Bashkir (Russia)
//	 365   | RUB Tatar (Russia)
//	 366   | S/. Quechua (Peru)
//	 367   | S/. Spanish (Peru)
//	 368   | SEK Lule Sami (Sweden)
//	 369   | SEK Southern Sami (Sweden)
//	 370   | soʻm Latin, Uzbek (Uzbekistan)
//	 371   | soʻm Uzbek (Uzbekistan)
//	 372   | SYP Syriac (Syria)
//	 373   | THB Thai (Thailand)
//	 374   | TMT Turkmen (Turkmenistan)
//	 375   | US$ English (Zimbabwe)
//	 376   | ZAR Northern Sotho (South Africa)
//	 377   | ZAR Southern Sotho (South Africa)
//	 378   | ZAR Tsonga (South Africa)
//	 379   | ZAR Tswana (south Africa)
//	 380   | ZAR Venda (South Africa)
//	 381   | ZAR Xhosa (South Africa)
//	 382   | zł Polish (Poland)
//	 383   | ден Macedonian (Macedonia)
//	 384   | KM Cyrillic, Bosnian (Bosnia & Herzegovina)
//	 385   | KM Serbian (Bosnia & Herzegovina)
//	 386   | лв. Bulgarian (Bulgaria)
//	 387   | p. Belarusian (Belarus)
//	 388   | сом Kyrgyz (Kyrgyzstan)
//	 389   | сом Tajik (Tajikistan)
//	 390   | ج.م. Arabic (Egypt)
//	 391   | د.أ. Arabic (Jordan)
//	 392   | د.أ. Arabic (United Arab Emirates)
//	 393   | د.ب. Arabic (Bahrain)
//	 394   | د.ت. Arabic (Tunisia)
//	 395   | د.ج. Arabic (Algeria)
//	 396   | د.ع. Arabic (Iraq)
//	 397   | د.ك. Arabic (Kuwait)
//	 398   | د.ل. Arabic (Libya)
//	 399   | د.م. Arabic (Morocco)
//	 400   | ر Punjabi (Pakistan)
//	 401   | ر.س. Arabic (Saudi Arabia)
//	 402   | ر.ع. Arabic (Oman)
//	 403   | ر.ق. Arabic (Qatar)
//	 404   | ر.ي. Arabic (Yemen)
//	 405   | ریال Persian (Iran)
//	 406   | ل.س. Arabic (Syria)
//	 407   | ل.ل. Arabic (Lebanon)
//	 408   | ብር Amharic (Ethiopia)
//	 409   | रू Nepaol (Nepal)
//	 410   | රු. Sinhala (Sri Lanka)
//	 411   | ADP
//	 412   | AED
//	 413   | AFA
//	 414   | AFN
//	 415   | ALL
//	 416   | AMD
//	 417   | ANG
//	 418   | AOA
//	 419   | ARS
//	 420   | ATS
//	 421   | AUD
//	 422   | AWG
//	 423   | AZM
//	 424   | AZN
//	 425   | BAM
//	 426   | BBD
//	 427   | BDT
//	 428   | BEF
//	 429   | BGL
//	 430   | BGN
//	 431   | BHD
//	 432   | BIF
//	 433   | BMD
//	 434   | BND
//	 435   | BOB
//	 436   | BOV
//	 437   | BRL
//	 438   | BSD
//	 439   | BTN
//	 440   | BWP
//	 441   | BYR
//	 442   | BZD
//	 443   | CAD
//	 444   | CDF
//	 445   | CHE
//	 446   | CHF
//	 447   | CHW
//	 448   | CLF
//	 449   | CLP
//	 450   | CNY
//	 451   | COP
//	 452   | COU
//	 453   | CRC
//	 454   | CSD
//	 455   | CUC
//	 456   | CVE
//	 457   | CYP
//	 458   | CZK
//	 459   | DEM
//	 460   | DJF
//	 461   | DKK
//	 462   | DOP
//	 463   | DZD
//	 464   | ECS
//	 465   | ECV
//	 466   | EEK
//	 467   | EGP
//	 468   | ERN
//	 469   | ESP
//	 470   | ETB
//	 471   | EUR
//	 472   | FIM
//	 473   | FJD
//	 474   | FKP
//	 475   | FRF
//	 476   | GBP
//	 477   | GEL
//	 478   | GHC
//	 479   | GHS
//	 480   | GIP
//	 481   | GMD
//	 482   | GNF
//	 483   | GRD
//	 484   | GTQ
//	 485   | GYD
//	 486   | HKD
//	 487   | HNL
//	 488   | HRK
//	 489   | HTG
//	 490   | HUF
//	 491   | IDR
//	 492   | IEP
//	 493   | ILS
//	 494   | INR
//	 495   | IQD
//	 496   | IRR
//	 497   | ISK
//	 498   | ITL
//	 499   | JMD
//	 500   | JOD
//	 501   | JPY
//	 502   | KAF
//	 503   | KES
//	 504   | KGS
//	 505   | KHR
//	 506   | KMF
//	 507   | KPW
//	 508   | KRW
//	 509   | KWD
//	 510   | KYD
//	 511   | KZT
//	 512   | LAK
//	 513   | LBP
//	 514   | LKR
//	 515   | LRD
//	 516   | LSL
//	 517   | LTL
//	 518   | LUF
//	 519   | LVL
//	 520   | LYD
//	 521   | MAD
//	 522   | MDL
//	 523   | MGA
//	 524   | MGF
//	 525   | MKD
//	 526   | MMK
//	 527   | MNT
//	 528   | MOP
//	 529   | MRO
//	 530   | MTL
//	 531   | MUR
//	 532   | MVR
//	 533   | MWK
//	 534   | MXN
//	 535   | MXV
//	 536   | MYR
//	 537   | MZM
//	 538   | MZN
//	 539   | NAD
//	 540   | NGN
//	 541   | NIO
//	 542   | NLG
//	 543   | NOK
//	 544   | NPR
//	 545   | NTD
//	 546   | NZD
//	 547   | OMR
//	 548   | PAB
//	 549   | PEN
//	 550   | PGK
//	 551   | PHP
//	 552   | PKR
//	 553   | PLN
//	 554   | PTE
//	 555   | PYG
//	 556   | QAR
//	 557   | ROL
//	 558   | RON
//	 559   | RSD
//	 560   | RUB
//	 561   | RUR
//	 562   | RWF
//	 563   | SAR
//	 564   | SBD
//	 565   | SCR
//	 566   | SDD
//	 567   | SDG
//	 568   | SDP
//	 569   | SEK
//	 570   | SGD
//	 571   | SHP
//	 572   | SIT
//	 573   | SKK
//	 574   | SLL
//	 575   | SOS
//	 576   | SPL
//	 577   | SRD
//	 578   | SRG
//	 579   | STD
//	 580   | SVC
//	 581   | SYP
//	 582   | SZL
//	 583   | THB
//	 584   | TJR
//	 585   | TJS
//	 586   | TMM
//	 587   | TMT
//	 588   | TND
//	 589   | TOP
//	 590   | TRL
//	 591   | TRY
//	 592   | TTD
//	 593   | TWD
//	 594   | TZS
//	 595   | UAH
//	 596   | UGX
//	 597   | USD
//	 598   | USN
//	 599   | USS
//	 600   | UYI
//	 601   | UYU
//	 602   | UZS
//	 603   | VEB
//	 604   | VEF
//	 605   | VND
//	 606   | VUV
//	 607   | WST
//	 608   | XAF
//	 609   | XAG
//	 610   | XAU
//	 611   | XB5
//	 612   | XBA
//	 613   | XBB
//	 614   | XBC
//	 615   | XBD
//	 616   | XCD
//	 617   | XDR
//	 618   | XFO
//	 619   | XFU
//	 620   | XOF
//	 621   | XPD
//	 622   | XPF
//	 623   | XPT
//	 624   | XTS
//	 625   | XXX
//	 626   | YER
//	 627   | YUM
//	 628   | ZAR
//	 629   | ZMK
//	 630   | ZMW
//	 631   | ZWD
//	 632   | ZWL
//	 633   | ZWN
//	 634   | ZWR
921
//
922
// Excelize support set custom number format for cell. For example, set number
923
// as date type in Uruguay (Spanish) format for Sheet1!A6:
924
//
925
//	f := excelize.NewFile()
xurime's avatar
xurime 已提交
926 927 928 929 930 931 932 933 934
//	defer func() {
//	    if err := f.Close(); err != nil {
//	        fmt.Println(err)
//	    }
//	}()
//	if err := f.SetCellValue("Sheet1", "A6", 42920.5); err != nil {
//	    fmt.Println(err)
//	    return
//	}
935 936
//	exp := "[$-380A]dddd\\,\\ dd\" de \"mmmm\" de \"yyyy;@"
//	style, err := f.NewStyle(&excelize.Style{CustomNumFmt: &exp})
xurime's avatar
xurime 已提交
937 938 939 940
//	if err != nil {
//	    fmt.Println(err)
//	    return
//	}
941
//	err = f.SetCellStyle("Sheet1", "A6", "A6", style)
942 943
//
// Cell Sheet1!A6 in the Excel Application: martes, 04 de Julio de 2017
944
func (f *File) NewStyle(style *Style) (int, error) {
945 946 947 948 949 950
	var (
		fs                                  *Style
		font                                *xlsxFont
		err                                 error
		cellXfsID, fontID, borderID, fillID int
	)
951 952 953
	if style == nil {
		return cellXfsID, err
	}
954 955 956
	fs, err = parseFormatStyleSet(style)
	if err != nil {
		return cellXfsID, err
957
	}
xurime's avatar
xurime 已提交
958 959
	if fs.DecimalPlaces != nil && (*fs.DecimalPlaces < 0 || *fs.DecimalPlaces > 30) {
		fs.DecimalPlaces = intPtr(2)
xurime's avatar
xurime 已提交
960
	}
xurime's avatar
xurime 已提交
961
	f.mu.Lock()
962 963
	s, err := f.stylesReader()
	if err != nil {
xurime's avatar
xurime 已提交
964
		f.mu.Unlock()
965 966
		return cellXfsID, err
	}
xurime's avatar
xurime 已提交
967
	f.mu.Unlock()
968 969
	s.mu.Lock()
	defer s.mu.Unlock()
970
	// check given style already exist.
971
	if cellXfsID, err = f.getStyleID(s, fs); err != nil || cellXfsID != -1 {
972 973 974 975
		return cellXfsID, err
	}

	numFmtID := newNumFmt(s, fs)
976 977

	if fs.Font != nil {
978
		fontID, _ = f.getFontID(s, fs)
979 980
		if fontID == -1 {
			s.Fonts.Count++
981 982
			font, _ = f.newFont(fs)
			s.Fonts.Font = append(s.Fonts.Font, font)
983 984
			fontID = s.Fonts.Count - 1
		}
985 986
	}

987 988 989 990 991 992 993 994 995 996
	borderID = getBorderID(s, fs)
	if borderID == -1 {
		if len(fs.Border) == 0 {
			borderID = 0
		} else {
			s.Borders.Count++
			s.Borders.Border = append(s.Borders.Border, newBorders(fs))
			borderID = s.Borders.Count - 1
		}
	}
997

998 999 1000 1001 1002 1003 1004 1005
	if fillID = getFillID(s, fs); fillID == -1 {
		if fill := newFills(fs, true); fill != nil {
			s.Fills.Count++
			s.Fills.Fill = append(s.Fills.Fill, fill)
			fillID = s.Fills.Count - 1
		} else {
			fillID = 0
		}
1006
	}
1007

1008 1009
	applyAlignment, alignment := fs.Alignment != nil, newAlignment(fs)
	applyProtection, protection := fs.Protection != nil, newProtection(fs)
1010
	return setCellXfs(s, fontID, numFmtID, fillID, borderID, applyAlignment, applyProtection, alignment, protection)
1011 1012
}

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
var (
	// styleBorders list all types of the cell border style.
	styleBorders = []string{
		"none",
		"thin",
		"medium",
		"dashed",
		"dotted",
		"thick",
		"double",
		"hair",
		"mediumDashed",
		"dashDot",
		"mediumDashDot",
		"dashDotDot",
		"mediumDashDotDot",
		"slantDashDot",
	}
	// styleBorderTypes list all types of the cell border.
	styleBorderTypes = []string{
		"left", "right", "top", "bottom", "diagonalUp", "diagonalDown",
	}
	// styleFillPatterns list all types of the cell fill style.
	styleFillPatterns = []string{
		"none",
		"solid",
		"mediumGray",
		"darkGray",
		"lightGray",
		"darkHorizontal",
		"darkVertical",
		"darkDown",
		"darkUp",
		"darkGrid",
		"darkTrellis",
		"lightHorizontal",
		"lightVertical",
		"lightDown",
		"lightUp",
		"lightGrid",
		"lightTrellis",
		"gray125",
		"gray0625",
	}
	// styleFillVariants list all preset variants of the fill style.
	styleFillVariants = []xlsxGradientFill{
		{Degree: 90, Stop: []*xlsxGradientFillStop{{}, {Position: 1}}},
		{Degree: 270, Stop: []*xlsxGradientFillStop{{}, {Position: 1}}},
		{Degree: 90, Stop: []*xlsxGradientFillStop{{}, {Position: 0.5}, {Position: 1}}},
		{Stop: []*xlsxGradientFillStop{{}, {Position: 1}}},
		{Degree: 180, Stop: []*xlsxGradientFillStop{{}, {Position: 1}}},
		{Stop: []*xlsxGradientFillStop{{}, {Position: 0.5}, {Position: 1}}},
		{Degree: 45, Stop: []*xlsxGradientFillStop{{}, {Position: 1}}},
		{Degree: 255, Stop: []*xlsxGradientFillStop{{}, {Position: 1}}},
		{Degree: 45, Stop: []*xlsxGradientFillStop{{}, {Position: 0.5}, {Position: 1}}},
		{Degree: 135, Stop: []*xlsxGradientFillStop{{}, {Position: 1}}},
		{Degree: 315, Stop: []*xlsxGradientFillStop{{}, {Position: 1}}},
		{Degree: 135, Stop: []*xlsxGradientFillStop{{}, {Position: 0.5}, {Position: 1}}},
		{Stop: []*xlsxGradientFillStop{{}, {Position: 1}}, Type: "path"},
		{Stop: []*xlsxGradientFillStop{{}, {Position: 1}}, Type: "path", Left: 1, Right: 1},
		{Stop: []*xlsxGradientFillStop{{}, {Position: 1}}, Type: "path", Bottom: 1, Top: 1},
		{Stop: []*xlsxGradientFillStop{{}, {Position: 1}}, Type: "path", Bottom: 1, Left: 1, Right: 1, Top: 1},
		{Stop: []*xlsxGradientFillStop{{}, {Position: 1}}, Type: "path", Bottom: 0.5, Left: 0.5, Right: 0.5, Top: 0.5},
	}
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
	// getXfIDFuncs provides a function to get xfID by given style.
	getXfIDFuncs = map[string]func(int, xlsxXf, *Style) bool{
		"numFmt": func(numFmtID int, xf xlsxXf, style *Style) bool {
			if style.CustomNumFmt == nil && numFmtID == -1 {
				return xf.NumFmtID != nil && *xf.NumFmtID == 0
			}
			if style.NegRed || (style.DecimalPlaces != nil && *style.DecimalPlaces != 2) {
				return false
			}
			return xf.NumFmtID != nil && *xf.NumFmtID == numFmtID
		},
		"font": func(fontID int, xf xlsxXf, style *Style) bool {
			if style.Font == nil {
				return (xf.FontID == nil || *xf.FontID == 0) && (xf.ApplyFont == nil || !*xf.ApplyFont)
			}
			return xf.FontID != nil && *xf.FontID == fontID && xf.ApplyFont != nil && *xf.ApplyFont
		},
		"fill": func(fillID int, xf xlsxXf, style *Style) bool {
			if style.Fill.Type == "" {
				return (xf.FillID == nil || *xf.FillID == 0) && (xf.ApplyFill == nil || !*xf.ApplyFill)
			}
			return xf.FillID != nil && *xf.FillID == fillID && xf.ApplyFill != nil && *xf.ApplyFill
		},
		"border": func(borderID int, xf xlsxXf, style *Style) bool {
			if len(style.Border) == 0 {
				return (xf.BorderID == nil || *xf.BorderID == 0) && (xf.ApplyBorder == nil || !*xf.ApplyBorder)
			}
			return xf.BorderID != nil && *xf.BorderID == borderID && xf.ApplyBorder != nil && *xf.ApplyBorder
		},
		"alignment": func(ID int, xf xlsxXf, style *Style) bool {
			if style.Alignment == nil {
				return xf.ApplyAlignment == nil || !*xf.ApplyAlignment
			}
			return reflect.DeepEqual(xf.Alignment, newAlignment(style))
		},
		"protection": func(ID int, xf xlsxXf, style *Style) bool {
			if style.Protection == nil {
				return xf.ApplyProtection == nil || !*xf.ApplyProtection
			}
			return reflect.DeepEqual(xf.Protection, newProtection(style)) && xf.ApplyProtection != nil && *xf.ApplyProtection
		},
	}
1119 1120 1121 1122
	// extractStyleCondFuncs provides a function set to returns if shoudle be
	// extract style definition by given style.
	extractStyleCondFuncs = map[string]func(xlsxXf, *xlsxStyleSheet) bool{
		"fill": func(xf xlsxXf, s *xlsxStyleSheet) bool {
xurime's avatar
xurime 已提交
1123
			return (xf.ApplyFill == nil || (xf.ApplyFill != nil && *xf.ApplyFill)) &&
1124 1125 1126 1127
				xf.FillID != nil && s.Fills != nil &&
				*xf.FillID < len(s.Fills.Fill)
		},
		"border": func(xf xlsxXf, s *xlsxStyleSheet) bool {
xurime's avatar
xurime 已提交
1128
			return (xf.ApplyBorder == nil || (xf.ApplyBorder != nil && *xf.ApplyBorder)) &&
1129 1130 1131 1132
				xf.BorderID != nil && s.Borders != nil &&
				*xf.BorderID < len(s.Borders.Border)
		},
		"font": func(xf xlsxXf, s *xlsxStyleSheet) bool {
xurime's avatar
xurime 已提交
1133
			return (xf.ApplyFont == nil || (xf.ApplyFont != nil && *xf.ApplyFont)) &&
1134 1135 1136 1137
				xf.FontID != nil && s.Fonts != nil &&
				*xf.FontID < len(s.Fonts.Font)
		},
		"alignment": func(xf xlsxXf, s *xlsxStyleSheet) bool {
xurime's avatar
xurime 已提交
1138
			return xf.ApplyAlignment == nil || (xf.ApplyAlignment != nil && *xf.ApplyAlignment)
1139 1140
		},
		"protection": func(xf xlsxXf, s *xlsxStyleSheet) bool {
xurime's avatar
xurime 已提交
1141
			return xf.ApplyProtection == nil || (xf.ApplyProtection != nil && *xf.ApplyProtection)
1142 1143
		},
	}
1144
	// drawContFmtFunc defines functions to create conditional formats.
1145 1146
	drawContFmtFunc = map[string]func(p int, ct, ref, GUID string, fmtCond *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule){
		"cellIs":            drawCondFmtCellIs,
1147
		"timePeriod":        drawCondFmtTimePeriod,
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
		"text":              drawCondFmtText,
		"top10":             drawCondFmtTop10,
		"aboveAverage":      drawCondFmtAboveAverage,
		"duplicateValues":   drawCondFmtDuplicateUniqueValues,
		"uniqueValues":      drawCondFmtDuplicateUniqueValues,
		"containsBlanks":    drawCondFmtBlanks,
		"notContainsBlanks": drawCondFmtNoBlanks,
		"containsErrors":    drawCondFmtErrors,
		"notContainsErrors": drawCondFmtNoErrors,
		"2_color_scale":     drawCondFmtColorScale,
		"3_color_scale":     drawCondFmtColorScale,
		"dataBar":           drawCondFmtDataBar,
		"expression":        drawCondFmtExp,
		"iconSet":           drawCondFmtIconSet,
1162 1163
	}
	// extractContFmtFunc defines functions to get conditional formats.
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
	extractContFmtFunc = map[string]func(*File, *xlsxCfRule, *xlsxExtLst) ConditionalFormatOptions{
		"cellIs": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtCellIs(c, extLst)
		},
		"timePeriod": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtTimePeriod(c, extLst)
		},
		"containsText": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtText(c, extLst)
		},
		"notContainsText": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtText(c, extLst)
		},
		"beginsWith": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtText(c, extLst)
		},
		"endsWith": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtText(c, extLst)
		},
		"top10": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtTop10(c, extLst)
		},
		"aboveAverage": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtAboveAverage(c, extLst)
		},
		"duplicateValues": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtDuplicateUniqueValues(c, extLst)
		},
		"uniqueValues": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtDuplicateUniqueValues(c, extLst)
		},
		"containsBlanks": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtBlanks(c, extLst)
		},
		"notContainsBlanks": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtNoBlanks(c, extLst)
		},
		"containsErrors": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtErrors(c, extLst)
		},
		"notContainsErrors": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtNoErrors(c, extLst)
		},
		"colorScale": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtColorScale(c, extLst)
		},
		"dataBar": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtDataBar(c, extLst)
		},
		"expression": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtExp(c, extLst)
		},
		"iconSet": func(f *File, c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
			return f.extractCondFmtIconSet(c, extLst)
		},
1219
	}
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
	// validType defined the list of valid validation types.
	validType = map[string]string{
		"cell":          "cellIs",
		"average":       "aboveAverage",
		"duplicate":     "duplicateValues",
		"unique":        "uniqueValues",
		"top":           "top10",
		"bottom":        "top10",
		"text":          "text",
		"time_period":   "timePeriod",
		"blanks":        "containsBlanks",
		"no_blanks":     "notContainsBlanks",
		"errors":        "containsErrors",
		"no_errors":     "notContainsErrors",
		"2_color_scale": "2_color_scale",
		"3_color_scale": "3_color_scale",
		"data_bar":      "dataBar",
		"formula":       "expression",
		"icon_set":      "iconSet",
	}
	// criteriaType defined the list of valid criteria types.
	criteriaType = map[string]string{
		"!=":                       "notEqual",
		"<":                        "lessThan",
		"<=":                       "lessThanOrEqual",
		"<>":                       "notEqual",
		"=":                        "equal",
		"==":                       "equal",
		">":                        "greaterThan",
		">=":                       "greaterThanOrEqual",
		"begins with":              "beginsWith",
		"between":                  "between",
		"containing":               "containsText",
		"continue month":           "nextMonth",
		"continue week":            "nextWeek",
		"ends with":                "endsWith",
		"equal to":                 "equal",
		"greater than or equal to": "greaterThanOrEqual",
		"greater than":             "greaterThan",
		"last 7 days":              "last7Days",
		"last month":               "lastMonth",
		"last week":                "lastWeek",
		"less than or equal to":    "lessThanOrEqual",
		"less than":                "lessThan",
		"not between":              "notBetween",
		"not containing":           "notContains",
		"not equal to":             "notEqual",
		"this month":               "thisMonth",
		"this week":                "thisWeek",
		"today":                    "today",
		"tomorrow":                 "tomorrow",
		"yesterday":                "yesterday",
	}
	// operatorType defined the list of valid operator types.
	operatorType = map[string]string{
		"beginsWith":         "begins with",
		"between":            "between",
		"containsText":       "containing",
		"endsWith":           "ends with",
		"equal":              "equal to",
		"greaterThan":        "greater than",
		"greaterThanOrEqual": "greater than or equal to",
		"last7Days":          "last 7 days",
		"lastMonth":          "last month",
		"lastWeek":           "last week",
		"lessThan":           "less than",
		"lessThanOrEqual":    "less than or equal to",
		"nextMonth":          "continue month",
		"nextWeek":           "continue week",
		"notBetween":         "not between",
		"notContains":        "not containing",
		"notEqual":           "not equal to",
		"thisMonth":          "this month",
		"thisWeek":           "this week",
		"today":              "today",
		"tomorrow":           "tomorrow",
		"yesterday":          "yesterday",
	}
	// cellIsCriteriaType defined the list of valid criteria types used for
	// cellIs conditional formats.
	cellIsCriteriaType = []string{
		"equal",
		"notEqual",
		"greaterThan",
		"lessThan",
		"greaterThanOrEqual",
		"lessThanOrEqual",
		"containsText",
		"notContains",
		"beginsWith",
		"endsWith",
	}
	// cfvo3 defined the icon set conditional formatting rules.
	cfvo3 = &xlsxCfRule{IconSet: &xlsxIconSet{Cfvo: []*xlsxCfvo{
		{Type: "percent", Val: "0"},
		{Type: "percent", Val: "33"},
		{Type: "percent", Val: "67"},
	}}}
	// cfvo4 defined the icon set conditional formatting rules.
	cfvo4 = &xlsxCfRule{IconSet: &xlsxIconSet{Cfvo: []*xlsxCfvo{
		{Type: "percent", Val: "0"},
		{Type: "percent", Val: "25"},
		{Type: "percent", Val: "50"},
		{Type: "percent", Val: "75"},
	}}}
	// cfvo5 defined the icon set conditional formatting rules.
	cfvo5 = &xlsxCfRule{IconSet: &xlsxIconSet{Cfvo: []*xlsxCfvo{
		{Type: "percent", Val: "0"},
		{Type: "percent", Val: "20"},
		{Type: "percent", Val: "40"},
		{Type: "percent", Val: "60"},
		{Type: "percent", Val: "80"},
	}}}
	// condFmtIconSetPresets defined the list of icon set conditional formatting
	// rules.
	condFmtIconSetPresets = map[string]*xlsxCfRule{
		"3Arrows":         cfvo3,
		"3ArrowsGray":     cfvo3,
		"3Flags":          cfvo3,
		"3Signs":          cfvo3,
		"3Symbols":        cfvo3,
		"3Symbols2":       cfvo3,
		"3TrafficLights1": cfvo3,
		"3TrafficLights2": cfvo3,
		"4Arrows":         cfvo4,
		"4ArrowsGray":     cfvo4,
		"4Rating":         cfvo4,
		"4RedToBlack":     cfvo4,
		"4TrafficLights":  cfvo4,
		"5Arrows":         cfvo5,
		"5ArrowsGray":     cfvo5,
		"5Quarters":       cfvo5,
		"5Rating":         cfvo5,
	}
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
)

// getThemeColor provides a function to convert theme color or index color to
// RGB color.
func (f *File) getThemeColor(clr *xlsxColor) string {
	var RGB string
	if clr == nil || f.Theme == nil {
		return RGB
	}
	if clrScheme := f.Theme.ThemeElements.ClrScheme; clr.Theme != nil {
		if val, ok := map[int]*string{
			0: &clrScheme.Lt1.SysClr.LastClr,
			1: &clrScheme.Dk1.SysClr.LastClr,
			2: clrScheme.Lt2.SrgbClr.Val,
			3: clrScheme.Dk2.SrgbClr.Val,
			4: clrScheme.Accent1.SrgbClr.Val,
			5: clrScheme.Accent2.SrgbClr.Val,
			6: clrScheme.Accent3.SrgbClr.Val,
			7: clrScheme.Accent4.SrgbClr.Val,
			8: clrScheme.Accent5.SrgbClr.Val,
			9: clrScheme.Accent6.SrgbClr.Val,
		}[*clr.Theme]; ok && val != nil {
			return strings.TrimPrefix(ThemeColor(*val, clr.Tint), "FF")
		}
	}
	if len(clr.RGB) == 6 {
		return clr.RGB
	}
	if len(clr.RGB) == 8 {
		return strings.TrimPrefix(clr.RGB, "FF")
	}
1385
	if f.Styles.Colors != nil && f.Styles.Colors.IndexedColors != nil && clr.Indexed < len(f.Styles.Colors.IndexedColors.RgbColor) {
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
		return strings.TrimPrefix(ThemeColor(strings.TrimPrefix(f.Styles.Colors.IndexedColors.RgbColor[clr.Indexed].RGB, "FF"), clr.Tint), "FF")
	}
	if clr.Indexed < len(IndexedColorMapping) {
		return strings.TrimPrefix(ThemeColor(IndexedColorMapping[clr.Indexed], clr.Tint), "FF")
	}
	return RGB
}

// extractBorders provides a function to extract borders styles settings by
// given border styles definition.
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
func (f *File) extractBorders(bdr *xlsxBorder, s *xlsxStyleSheet, style *Style) {
	if bdr != nil {
		var borders []Border
		extractBorder := func(lineType string, line xlsxLine) {
			if line.Style != "" {
				borders = append(borders, Border{
					Type:  lineType,
					Color: f.getThemeColor(line.Color),
					Style: inStrSlice(styleBorders, line.Style, false),
				})
1406
			}
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
		}
		for i, line := range []xlsxLine{
			bdr.Left, bdr.Right, bdr.Top, bdr.Bottom, bdr.Diagonal, bdr.Diagonal,
		} {
			if i < 4 {
				extractBorder(styleBorderTypes[i], line)
			}
			if i == 4 && bdr.DiagonalUp {
				extractBorder(styleBorderTypes[i], line)
			}
			if i == 5 && bdr.DiagonalDown {
				extractBorder(styleBorderTypes[i], line)
1419 1420
			}
		}
1421
		style.Border = borders
1422 1423 1424 1425 1426
	}
}

// extractFills provides a function to extract fill styles settings by
// given fill styles definition.
1427 1428
func (f *File) extractFills(fl *xlsxFill, s *xlsxStyleSheet, style *Style) {
	if fl != nil {
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
		var fill Fill
		if fl.GradientFill != nil {
			fill.Type = "gradient"
			for shading, variants := range styleFillVariants {
				if fl.GradientFill.Bottom == variants.Bottom &&
					fl.GradientFill.Degree == variants.Degree &&
					fl.GradientFill.Left == variants.Left &&
					fl.GradientFill.Right == variants.Right &&
					fl.GradientFill.Top == variants.Top &&
					fl.GradientFill.Type == variants.Type {
					fill.Shading = shading
					break
				}
			}
			for _, stop := range fl.GradientFill.Stop {
				fill.Color = append(fill.Color, f.getThemeColor(&stop.Color))
			}
		}
		if fl.PatternFill != nil {
			fill.Type = "pattern"
			fill.Pattern = inStrSlice(styleFillPatterns, fl.PatternFill.PatternType, false)
1450 1451 1452
			if fl.PatternFill.BgColor != nil {
				fill.Color = []string{f.getThemeColor(fl.PatternFill.BgColor)}
			}
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
			if fl.PatternFill.FgColor != nil {
				fill.Color = []string{f.getThemeColor(fl.PatternFill.FgColor)}
			}
		}
		style.Fill = fill
	}
}

// extractFont provides a function to extract font styles settings by given
// font styles definition.
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
func (f *File) extractFont(fnt *xlsxFont, s *xlsxStyleSheet, style *Style) {
	if fnt != nil {
		var font Font
		if fnt.B != nil {
			font.Bold = fnt.B.Value()
		}
		if fnt.I != nil {
			font.Italic = fnt.I.Value()
		}
		if fnt.U != nil {
xurime's avatar
xurime 已提交
1473 1474 1475
			if font.Underline = fnt.U.Value(); font.Underline == "" {
				font.Underline = "single"
			}
1476
		}
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
		if fnt.Name != nil {
			font.Family = fnt.Name.Value()
		}
		if fnt.Sz != nil {
			font.Size = fnt.Sz.Value()
		}
		if fnt.Strike != nil {
			font.Strike = fnt.Strike.Value()
		}
		if fnt.Color != nil {
			font.Color = strings.TrimPrefix(fnt.Color.RGB, "FF")
			font.ColorIndexed = fnt.Color.Indexed
			font.ColorTheme = fnt.Color.Theme
			font.ColorTint = fnt.Color.Tint
		}
		style.Font = &font
1493 1494 1495 1496 1497
	}
}

// extractNumFmt provides a function to extract number format by given styles
// definition.
1498 1499 1500
func (f *File) extractNumFmt(n *int, s *xlsxStyleSheet, style *Style) {
	if n != nil {
		numFmtID := *n
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
		if _, ok := builtInNumFmt[numFmtID]; ok || isLangNumFmt(numFmtID) {
			style.NumFmt = numFmtID
			return
		}
		if s.NumFmts != nil {
			for _, numFmt := range s.NumFmts.NumFmt {
				style.CustomNumFmt = &numFmt.FormatCode
				if strings.Contains(numFmt.FormatCode, ";[Red]") {
					style.NegRed = true
				}
				for numFmtID, fmtCode := range currencyNumFmt {
					if style.NegRed {
						fmtCode += ";[Red]" + fmtCode
					}
					if numFmt.FormatCode == fmtCode {
						style.NumFmt = numFmtID
					}
				}
			}
		}
	}
}

// extractAlignment provides a function to extract alignment format by
// given style definition.
1526 1527
func (f *File) extractAlignment(a *xlsxAlignment, s *xlsxStyleSheet, style *Style) {
	if a != nil {
1528
		style.Alignment = &Alignment{
1529 1530 1531 1532 1533 1534 1535 1536 1537
			Horizontal:      a.Horizontal,
			Indent:          a.Indent,
			JustifyLastLine: a.JustifyLastLine,
			ReadingOrder:    a.ReadingOrder,
			RelativeIndent:  a.RelativeIndent,
			ShrinkToFit:     a.ShrinkToFit,
			TextRotation:    a.TextRotation,
			Vertical:        a.Vertical,
			WrapText:        a.WrapText,
1538 1539 1540 1541 1542 1543
		}
	}
}

// extractProtection provides a function to extract protection settings by
// given format definition.
1544 1545
func (f *File) extractProtection(p *xlsxProtection, s *xlsxStyleSheet, style *Style) {
	if p != nil {
1546
		style.Protection = &Protection{}
1547 1548
		if p.Hidden != nil {
			style.Protection.Hidden = *p.Hidden
1549
		}
1550 1551
		if p.Locked != nil {
			style.Protection.Locked = *p.Locked
1552 1553 1554 1555
		}
	}
}

1556
// GetStyle provides a function to get style definition by given style index.
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
func (f *File) GetStyle(idx int) (*Style, error) {
	var style *Style
	f.mu.Lock()
	s, err := f.stylesReader()
	if err != nil {
		return style, err
	}
	f.mu.Unlock()
	if idx < 0 || s.CellXfs == nil || len(s.CellXfs.Xf) <= idx {
		return style, newInvalidStyleID(idx)
	}
	style = &Style{}
	xf := s.CellXfs.Xf[idx]
1570 1571 1572 1573 1574 1575 1576 1577
	if extractStyleCondFuncs["fill"](xf, s) {
		f.extractFills(s.Fills.Fill[*xf.FillID], s, style)
	}
	if extractStyleCondFuncs["border"](xf, s) {
		f.extractBorders(s.Borders.Border[*xf.BorderID], s, style)
	}
	if extractStyleCondFuncs["font"](xf, s) {
		f.extractFont(s.Fonts.Font[*xf.FontID], s, style)
1578
	}
1579 1580 1581 1582 1583 1584 1585
	if extractStyleCondFuncs["alignment"](xf, s) {
		f.extractAlignment(xf.Alignment, s, style)
	}
	if extractStyleCondFuncs["protection"](xf, s) {
		f.extractProtection(xf.Protection, s, style)
	}
	f.extractNumFmt(xf.NumFmtID, s, style)
1586 1587 1588
	return style, nil
}

1589
// getStyleID provides a function to get styleID by given style. If given
1590
// style does not exist, will return -1.
1591 1592 1593 1594 1595 1596
func (f *File) getStyleID(ss *xlsxStyleSheet, style *Style) (int, error) {
	var (
		err     error
		fontID  int
		styleID = -1
	)
1597
	if ss.CellXfs == nil {
1598 1599 1600 1601 1602
		return styleID, err
	}
	numFmtID, borderID, fillID := getNumFmtID(ss, style), getBorderID(ss, style), getFillID(ss, style)
	if fontID, err = f.getFontID(ss, style); err != nil {
		return styleID, err
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
	}
	if style.CustomNumFmt != nil {
		numFmtID = getCustomNumFmtID(ss, style)
	}
	for xfID, xf := range ss.CellXfs.Xf {
		if getXfIDFuncs["numFmt"](numFmtID, xf, style) &&
			getXfIDFuncs["font"](fontID, xf, style) &&
			getXfIDFuncs["fill"](fillID, xf, style) &&
			getXfIDFuncs["border"](borderID, xf, style) &&
			getXfIDFuncs["alignment"](0, xf, style) &&
			getXfIDFuncs["protection"](0, xf, style) {
			styleID = xfID
1615
			return styleID, err
1616 1617
		}
	}
1618
	return styleID, err
1619 1620
}

xurime's avatar
xurime 已提交
1621
// NewConditionalStyle provides a function to create style for conditional
1622
// format by given style format. The parameters are the same with the NewStyle
1623 1624
// function.
func (f *File) NewConditionalStyle(style *Style) (int, error) {
xurime's avatar
xurime 已提交
1625
	f.mu.Lock()
1626 1627
	s, err := f.stylesReader()
	if err != nil {
xurime's avatar
xurime 已提交
1628
		f.mu.Unlock()
1629 1630
		return 0, err
	}
xurime's avatar
xurime 已提交
1631
	f.mu.Unlock()
1632 1633 1634 1635
	fs, err := parseFormatStyleSet(style)
	if err != nil {
		return 0, err
	}
1636 1637 1638 1639
	if fs.DecimalPlaces != nil && (*fs.DecimalPlaces < 0 || *fs.DecimalPlaces > 30) {
		fs.DecimalPlaces = intPtr(2)
	}
	dxf := xlsxDxf{
1640
		Fill: newFills(fs, false),
1641 1642
	}
	if fs.Alignment != nil {
1643
		dxf.Alignment = newAlignment(fs)
1644 1645
	}
	if len(fs.Border) > 0 {
1646
		dxf.Border = newBorders(fs)
1647 1648
	}
	if fs.Font != nil {
1649
		dxf.Font, _ = f.newFont(fs)
1650
	}
1651 1652 1653 1654
	if fs.Protection != nil {
		dxf.Protection = newProtection(fs)
	}
	dxf.NumFmt = newDxfNumFmt(s, style, &dxf)
1655 1656
	if s.Dxfs == nil {
		s.Dxfs = &xlsxDxfs{}
1657
	}
1658
	s.Dxfs.Count++
1659
	s.Dxfs.Dxfs = append(s.Dxfs.Dxfs, &dxf)
1660 1661 1662
	return s.Dxfs.Count - 1, nil
}

1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
// GetConditionalStyle returns conditional format style definition by specified
// style index.
func (f *File) GetConditionalStyle(idx int) (*Style, error) {
	var style *Style
	f.mu.Lock()
	s, err := f.stylesReader()
	if err != nil {
		return style, err
	}
	f.mu.Unlock()
	if idx < 0 || s.Dxfs == nil || len(s.Dxfs.Dxfs) <= idx {
		return style, newInvalidStyleID(idx)
	}
	style = &Style{}
	xf := s.Dxfs.Dxfs[idx]
1678 1679 1680 1681
	// The default pattern fill type of conditional format style is solid
	if xf.Fill != nil && xf.Fill.PatternFill != nil && xf.Fill.PatternFill.PatternType == "" {
		xf.Fill.PatternFill.PatternType = "solid"
	}
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
	f.extractFills(xf.Fill, s, style)
	f.extractBorders(xf.Border, s, style)
	f.extractFont(xf.Font, s, style)
	f.extractAlignment(xf.Alignment, s, style)
	f.extractProtection(xf.Protection, s, style)
	if xf.NumFmt != nil {
		f.extractNumFmt(&xf.NumFmt.NumFmtID, s, style)
	}
	return style, nil
}

1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
// newDxfNumFmt provides a function to create number format for conditional
// format styles.
func newDxfNumFmt(styleSheet *xlsxStyleSheet, style *Style, dxf *xlsxDxf) *xlsxNumFmt {
	dp, numFmtID := "0", 164 // Default custom number format code from 164.
	if style.DecimalPlaces != nil && *style.DecimalPlaces > 0 {
		dp += "."
		for i := 0; i < *style.DecimalPlaces; i++ {
			dp += "0"
		}
	}
	if style.CustomNumFmt != nil {
		if styleSheet.Dxfs != nil {
			for _, d := range styleSheet.Dxfs.Dxfs {
				if d != nil && d.NumFmt != nil && d.NumFmt.NumFmtID > numFmtID {
					numFmtID = d.NumFmt.NumFmtID
				}
			}
		}
		return &xlsxNumFmt{NumFmtID: numFmtID + 1, FormatCode: *style.CustomNumFmt}
	}
	numFmtCode, ok := builtInNumFmt[style.NumFmt]
	if style.NumFmt > 0 && ok {
		return &xlsxNumFmt{NumFmtID: style.NumFmt, FormatCode: numFmtCode}
	}
	fc, currency := currencyNumFmt[style.NumFmt]
	if !currency {
		return nil
	}
	if style.DecimalPlaces != nil {
		fc = strings.ReplaceAll(fc, "0.00", dp)
	}
	if style.NegRed {
		fc = fc + ";[Red]" + fc
	}
	return &xlsxNumFmt{NumFmtID: numFmtID, FormatCode: fc}
}

xurime's avatar
xurime 已提交
1730 1731
// GetDefaultFont provides the default font name currently set in the
// workbook. The spreadsheet generated by excelize default font is Calibri.
1732 1733 1734 1735 1736 1737
func (f *File) GetDefaultFont() (string, error) {
	font, err := f.readDefaultFont()
	if err != nil {
		return "", err
	}
	return *font.Name.Val, err
1738 1739
}

xurime's avatar
xurime 已提交
1740
// SetDefaultFont changes the default font in the workbook.
1741 1742 1743 1744 1745
func (f *File) SetDefaultFont(fontName string) error {
	font, err := f.readDefaultFont()
	if err != nil {
		return err
	}
1746
	font.Name.Val = stringPtr(fontName)
xurime's avatar
xurime 已提交
1747
	f.mu.Lock()
1748
	s, _ := f.stylesReader()
xurime's avatar
xurime 已提交
1749
	f.mu.Unlock()
1750 1751 1752
	s.Fonts.Font[0] = font
	custom := true
	s.CellStyles.CellStyle[0].CustomBuiltIn = &custom
1753
	return err
1754 1755
}

1756
// readDefaultFont provides an un-marshalled font value.
1757
func (f *File) readDefaultFont() (*xlsxFont, error) {
xurime's avatar
xurime 已提交
1758 1759
	f.mu.Lock()
	defer f.mu.Unlock()
1760 1761 1762 1763 1764
	s, err := f.stylesReader()
	if err != nil {
		return nil, err
	}
	return s.Fonts.Font[0], err
1765 1766
}

1767
// getFontID provides a function to get font ID.
1768
// If given font does not exist, will return -1.
1769 1770 1771
func (f *File) getFontID(styleSheet *xlsxStyleSheet, style *Style) (int, error) {
	var err error
	fontID := -1
1772
	if styleSheet.Fonts == nil || style.Font == nil {
1773
		return fontID, err
1774 1775
	}
	for idx, fnt := range styleSheet.Fonts.Font {
1776 1777 1778 1779 1780
		font, err := f.newFont(style)
		if err != nil {
			return fontID, err
		}
		if reflect.DeepEqual(*fnt, *font) {
1781
			fontID = idx
1782
			return fontID, err
1783 1784
		}
	}
1785
	return fontID, err
1786 1787
}

1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
// newFontColor set font color by given styles.
func newFontColor(font *Font) *xlsxColor {
	var fontColor *xlsxColor
	prepareFontColor := func() {
		if fontColor != nil {
			return
		}
		fontColor = &xlsxColor{}
	}
	if font.Color != "" {
		prepareFontColor()
		fontColor.RGB = getPaletteColor(font.Color)
	}
1801 1802 1803 1804
	if font.ColorIndexed >= 0 && font.ColorIndexed <= len(IndexedColorMapping)+1 {
		prepareFontColor()
		fontColor.Indexed = font.ColorIndexed
	}
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
	if font.ColorTheme != nil {
		prepareFontColor()
		fontColor.Theme = font.ColorTheme
	}
	if font.ColorTint != 0 {
		prepareFontColor()
		fontColor.Tint = font.ColorTint
	}
	return fontColor
}

1816
// newFont provides a function to add font style by given cell format
xurime's avatar
xurime 已提交
1817
// settings.
1818 1819
func (f *File) newFont(style *Style) (*xlsxFont, error) {
	var err error
1820
	if style.Font.Size < MinFontSize {
1821
		style.Font.Size = 11
1822
	}
1823
	fnt := xlsxFont{
1824 1825
		Sz:     &attrValFloat{Val: float64Ptr(style.Font.Size)},
		Name:   &attrValString{Val: stringPtr(style.Font.Family)},
1826
		Family: &attrValInt{Val: intPtr(2)},
1827
	}
1828
	fnt.Color = newFontColor(style.Font)
1829
	if style.Font.Bold {
1830
		fnt.B = &attrValBool{Val: &style.Font.Bold}
1831
	}
1832
	if style.Font.Italic {
1833
		fnt.I = &attrValBool{Val: &style.Font.Italic}
1834
	}
1835
	if *fnt.Name.Val == "" {
1836 1837 1838
		if *fnt.Name.Val, err = f.GetDefaultFont(); err != nil {
			return &fnt, err
		}
1839
	}
1840
	if style.Font.Strike {
1841
		fnt.Strike = &attrValBool{Val: &style.Font.Strike}
xurime's avatar
xurime 已提交
1842
	}
1843 1844
	if idx := inStrSlice(supportedUnderlineTypes, style.Font.Underline, true); idx != -1 {
		fnt.U = &attrValString{Val: stringPtr(supportedUnderlineTypes[idx])}
1845
	}
1846
	return &fnt, err
1847 1848
}

xurime's avatar
xurime 已提交
1849
// getNumFmtID provides a function to get number format code ID.
1850
// If given number format code does not exist, will return -1.
xurime's avatar
xurime 已提交
1851 1852 1853 1854 1855
func getNumFmtID(styleSheet *xlsxStyleSheet, style *Style) (numFmtID int) {
	numFmtID = -1
	if _, ok := builtInNumFmt[style.NumFmt]; ok {
		return style.NumFmt
	}
1856 1857 1858
	if (27 <= style.NumFmt && style.NumFmt <= 36) || (50 <= style.NumFmt && style.NumFmt <= 81) {
		numFmtID = style.NumFmt
		return
1859
	}
xurime's avatar
xurime 已提交
1860
	if fmtCode, ok := currencyNumFmt[style.NumFmt]; ok {
xurime's avatar
xurime 已提交
1861 1862 1863 1864 1865 1866 1867
		numFmtID = style.NumFmt
		if styleSheet.NumFmts != nil {
			for _, numFmt := range styleSheet.NumFmts.NumFmt {
				if numFmt.FormatCode == fmtCode {
					numFmtID = numFmt.NumFmtID
					return
				}
xurime's avatar
xurime 已提交
1868 1869 1870 1871 1872 1873
			}
		}
	}
	return
}

1874
// newNumFmt provides a function to check if number format code in the range
xurime's avatar
xurime 已提交
1875
// of built-in values.
1876
func newNumFmt(styleSheet *xlsxStyleSheet, style *Style) int {
xurime's avatar
xurime 已提交
1877 1878 1879 1880 1881 1882
	dp, numFmtID := "0", 164 // Default custom number format code from 164.
	if style.DecimalPlaces != nil && *style.DecimalPlaces > 0 {
		dp += "."
		for i := 0; i < *style.DecimalPlaces; i++ {
			dp += "0"
		}
1883
	}
1884
	if style.CustomNumFmt != nil {
1885 1886 1887
		if customNumFmtID := getCustomNumFmtID(styleSheet, style); customNumFmtID != -1 {
			return customNumFmtID
		}
1888
		return setCustomNumFmt(styleSheet, style)
1889
	}
xurime's avatar
xurime 已提交
1890
	if _, ok := builtInNumFmt[style.NumFmt]; !ok {
1891
		fc, currency := currencyNumFmt[style.NumFmt]
1892
		if !currency {
1893
			return setLangNumFmt(style)
1894
		}
xurime's avatar
xurime 已提交
1895 1896 1897
		if style.DecimalPlaces != nil {
			fc = strings.ReplaceAll(fc, "0.00", dp)
		}
1898
		if style.NegRed {
1899 1900
			fc = fc + ";[Red]" + fc
		}
xurime's avatar
xurime 已提交
1901 1902
		if styleSheet.NumFmts == nil {
			styleSheet.NumFmts = &xlsxNumFmts{NumFmt: []*xlsxNumFmt{}}
1903
		} else {
xurime's avatar
xurime 已提交
1904
			numFmtID = styleSheet.NumFmts.NumFmt[len(styleSheet.NumFmts.NumFmt)-1].NumFmtID + 1
1905
		}
xurime's avatar
xurime 已提交
1906 1907 1908 1909
		styleSheet.NumFmts.NumFmt = append(styleSheet.NumFmts.NumFmt, &xlsxNumFmt{
			FormatCode: fc, NumFmtID: numFmtID,
		})
		styleSheet.NumFmts.Count++
1910 1911
		return numFmtID
	}
1912
	return style.NumFmt
1913 1914
}

xurime's avatar
xurime 已提交
1915
// setCustomNumFmt provides a function to set custom number format code.
1916
func setCustomNumFmt(styleSheet *xlsxStyleSheet, style *Style) int {
1917 1918 1919 1920 1921 1922 1923
	nf := xlsxNumFmt{NumFmtID: 163, FormatCode: *style.CustomNumFmt}
	if styleSheet.NumFmts == nil {
		styleSheet.NumFmts = &xlsxNumFmts{}
	}
	for _, numFmt := range styleSheet.NumFmts.NumFmt {
		if numFmt != nil && nf.NumFmtID < numFmt.NumFmtID {
			nf.NumFmtID = numFmt.NumFmtID
1924 1925
		}
	}
1926 1927 1928
	nf.NumFmtID++
	styleSheet.NumFmts.NumFmt = append(styleSheet.NumFmts.NumFmt, &nf)
	styleSheet.NumFmts.Count = len(styleSheet.NumFmts.NumFmt)
1929 1930 1931
	return nf.NumFmtID
}

1932
// getCustomNumFmtID provides a function to get custom number format code ID.
1933
// If given custom number format code does not exist, will return -1.
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
func getCustomNumFmtID(styleSheet *xlsxStyleSheet, style *Style) (customNumFmtID int) {
	customNumFmtID = -1
	if styleSheet.NumFmts == nil {
		return
	}
	for _, numFmt := range styleSheet.NumFmts.NumFmt {
		if style.CustomNumFmt != nil && numFmt.FormatCode == *style.CustomNumFmt {
			customNumFmtID = numFmt.NumFmtID
			return
		}
	}
	return
}

1948 1949 1950 1951 1952 1953
// isLangNumFmt provides a function to returns if a given number format ID is a
// built-in language glyphs number format code.
func isLangNumFmt(ID int) bool {
	return (27 <= ID && ID <= 36) || (50 <= ID && ID <= 62) || (67 <= ID && ID <= 81)
}

xurime's avatar
xurime 已提交
1954
// setLangNumFmt provides a function to set number format code with language.
1955
func setLangNumFmt(style *Style) int {
1956
	if isLangNumFmt(style.NumFmt) {
1957
		return style.NumFmt
1958
	}
1959
	return 0
xurime's avatar
xurime 已提交
1960 1961
}

1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
// getFillID provides a function to get fill ID. If given fill is not
// exist, will return -1.
func getFillID(styleSheet *xlsxStyleSheet, style *Style) (fillID int) {
	fillID = -1
	if styleSheet.Fills == nil || style.Fill.Type == "" {
		return
	}
	fills := newFills(style, true)
	if fills == nil {
		return
	}
	for idx, fill := range styleSheet.Fills.Fill {
		if reflect.DeepEqual(fill, fills) {
			fillID = idx
			return
		}
	}
	return
}

// newFills provides a function to add fill elements in the styles.xml by
xurime's avatar
xurime 已提交
1983
// given cell format settings.
1984
func newFills(style *Style, fg bool) *xlsxFill {
1985
	var fill xlsxFill
1986
	switch style.Fill.Type {
1987
	case "gradient":
1988
		if len(style.Fill.Color) != 2 || style.Fill.Shading < 0 || style.Fill.Shading > 16 {
1989 1990
			break
		}
1991
		gradient := styleFillVariants[style.Fill.Shading]
1992 1993 1994 1995
		gradient.Stop[0].Color.RGB = getPaletteColor(style.Fill.Color[0])
		gradient.Stop[1].Color.RGB = getPaletteColor(style.Fill.Color[1])
		if len(gradient.Stop) == 3 {
			gradient.Stop[2].Color.RGB = getPaletteColor(style.Fill.Color[0])
1996 1997 1998
		}
		fill.GradientFill = &gradient
	case "pattern":
1999
		if style.Fill.Pattern > 18 || style.Fill.Pattern < 0 {
2000 2001
			break
		}
2002
		if len(style.Fill.Color) < 1 {
2003
			break
2004
		}
2005
		var pattern xlsxPatternFill
2006
		pattern.PatternType = styleFillPatterns[style.Fill.Pattern]
2007
		if fg {
2008 2009 2010
			if pattern.FgColor == nil {
				pattern.FgColor = new(xlsxColor)
			}
2011
			pattern.FgColor.RGB = getPaletteColor(style.Fill.Color[0])
2012
		} else {
2013 2014 2015
			if pattern.BgColor == nil {
				pattern.BgColor = new(xlsxColor)
			}
2016
			pattern.BgColor.RGB = getPaletteColor(style.Fill.Color[0])
2017
		}
2018
		fill.PatternFill = &pattern
2019 2020
	default:
		return nil
2021
	}
2022
	return &fill
2023 2024
}

2025
// newAlignment provides a function to formatting information pertaining to
xurime's avatar
xurime 已提交
2026 2027 2028
// text alignment in cells. There are a variety of choices for how text is
// aligned both horizontally and vertically, as well as indentation settings,
// and so on.
2029
func newAlignment(style *Style) *xlsxAlignment {
2030
	var alignment xlsxAlignment
2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
	if style.Alignment != nil {
		alignment.Horizontal = style.Alignment.Horizontal
		alignment.Indent = style.Alignment.Indent
		alignment.JustifyLastLine = style.Alignment.JustifyLastLine
		alignment.ReadingOrder = style.Alignment.ReadingOrder
		alignment.RelativeIndent = style.Alignment.RelativeIndent
		alignment.ShrinkToFit = style.Alignment.ShrinkToFit
		alignment.TextRotation = style.Alignment.TextRotation
		alignment.Vertical = style.Alignment.Vertical
		alignment.WrapText = style.Alignment.WrapText
2041
	}
2042
	return &alignment
2043 2044
}

2045
// newProtection provides a function to set protection properties associated
2046
// with the cell.
2047
func newProtection(style *Style) *xlsxProtection {
2048
	var protection xlsxProtection
2049
	if style.Protection != nil {
2050 2051
		protection.Hidden = &style.Protection.Hidden
		protection.Locked = &style.Protection.Locked
2052 2053 2054 2055
	}
	return &protection
}

2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
// getBorderID provides a function to get border ID. If given border is not
// exist, will return -1.
func getBorderID(styleSheet *xlsxStyleSheet, style *Style) (borderID int) {
	borderID = -1
	if styleSheet.Borders == nil || len(style.Border) == 0 {
		return
	}
	for idx, border := range styleSheet.Borders.Border {
		if reflect.DeepEqual(*border, *newBorders(style)) {
			borderID = idx
			return
		}
	}
	return
}

// newBorders provides a function to add border elements in the styles.xml by
2073
// given borders format settings.
2074
func newBorders(style *Style) *xlsxBorder {
2075
	var border xlsxBorder
2076
	for _, v := range style.Border {
xurime's avatar
xurime 已提交
2077 2078 2079 2080 2081
		if 0 <= v.Style && v.Style < 14 {
			var color xlsxColor
			color.RGB = getPaletteColor(v.Color)
			switch v.Type {
			case "left":
2082
				border.Left.Style = styleBorders[v.Style]
xurime's avatar
xurime 已提交
2083 2084
				border.Left.Color = &color
			case "right":
2085
				border.Right.Style = styleBorders[v.Style]
xurime's avatar
xurime 已提交
2086 2087
				border.Right.Color = &color
			case "top":
2088
				border.Top.Style = styleBorders[v.Style]
xurime's avatar
xurime 已提交
2089 2090
				border.Top.Color = &color
			case "bottom":
2091
				border.Bottom.Style = styleBorders[v.Style]
xurime's avatar
xurime 已提交
2092 2093
				border.Bottom.Color = &color
			case "diagonalUp":
2094
				border.Diagonal.Style = styleBorders[v.Style]
xurime's avatar
xurime 已提交
2095 2096 2097
				border.Diagonal.Color = &color
				border.DiagonalUp = true
			case "diagonalDown":
2098
				border.Diagonal.Style = styleBorders[v.Style]
xurime's avatar
xurime 已提交
2099 2100 2101
				border.Diagonal.Color = &color
				border.DiagonalDown = true
			}
2102 2103
		}
	}
2104
	return &border
2105 2106
}

2107
// setCellXfs provides a function to set describes all the formatting for a
2108
// cell.
2109
func setCellXfs(style *xlsxStyleSheet, fontID, numFmtID, fillID, borderID int, applyAlignment, applyProtection bool, alignment *xlsxAlignment, protection *xlsxProtection) (int, error) {
2110
	var xf xlsxXf
2111
	xf.FontID = intPtr(fontID)
2112
	if fontID != 0 {
2113
		xf.ApplyFont = boolPtr(true)
2114
	}
2115
	xf.NumFmtID = intPtr(numFmtID)
xurime's avatar
xurime 已提交
2116
	if numFmtID != 0 {
2117
		xf.ApplyNumberFormat = boolPtr(true)
xurime's avatar
xurime 已提交
2118
	}
2119
	xf.FillID = intPtr(fillID)
2120 2121 2122
	if fillID != 0 {
		xf.ApplyFill = boolPtr(true)
	}
2123
	xf.BorderID = intPtr(borderID)
2124 2125 2126
	if borderID != 0 {
		xf.ApplyBorder = boolPtr(true)
	}
2127 2128 2129
	if len(style.CellXfs.Xf) == MaxCellStyles {
		return 0, ErrCellStyles
	}
2130
	style.CellXfs.Count = len(style.CellXfs.Xf) + 1
2131
	xf.Alignment = alignment
2132 2133 2134
	if alignment != nil {
		xf.ApplyAlignment = boolPtr(applyAlignment)
	}
2135
	if applyProtection {
2136
		xf.ApplyProtection = boolPtr(applyProtection)
2137 2138
		xf.Protection = protection
	}
2139 2140
	xfID := 0
	xf.XfID = &xfID
2141
	style.CellXfs.Xf = append(style.CellXfs.Xf, xf)
2142
	return style.CellXfs.Count - 1, nil
2143 2144
}

2145
// GetCellStyle provides a function to get cell style index by given worksheet
2146 2147
// name and cell reference.
func (f *File) GetCellStyle(sheet, cell string) (int, error) {
2148
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
2149 2150 2151
	if err != nil {
		return 0, err
	}
xurime's avatar
xurime 已提交
2152
	col, row, err := CellNameToCoordinates(cell)
2153 2154 2155
	if err != nil {
		return 0, err
	}
2156 2157 2158 2159
	ws.prepareSheetXML(col, row)
	ws.mu.Lock()
	defer ws.mu.Unlock()
	return ws.prepareCellStyle(col, row, ws.SheetData.Row[row-1].C[col-1].S), err
2160 2161
}

xurime's avatar
xurime 已提交
2162
// SetCellStyle provides a function to add style attribute for cells by given
2163
// worksheet name, range reference and style ID. This function is concurrency
2164
// safe. Note that diagonalDown and diagonalUp type border should be use same
2165
// color in the same range. SetCellStyle will overwrite the existing
2166
// styles for the cell, it won't append or merge style with existing styles.
2167 2168 2169
//
// For example create a borders of cell H9 on Sheet1:
//
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
//	style, err := f.NewStyle(&excelize.Style{
//	    Border: []excelize.Border{
//	        {Type: "left", Color: "0000FF", Style: 3},
//	        {Type: "top", Color: "00FF00", Style: 4},
//	        {Type: "bottom", Color: "FFFF00", Style: 5},
//	        {Type: "right", Color: "FF0000", Style: 6},
//	        {Type: "diagonalDown", Color: "A020F0", Style: 7},
//	        {Type: "diagonalUp", Color: "A020F0", Style: 8},
//	    },
//	})
//	if err != nil {
//	    fmt.Println(err)
//	}
//	err = f.SetCellStyle("Sheet1", "H9", "H9", style)
2184 2185 2186 2187
//
// Set gradient fill with vertical variants shading styles for cell H9 on
// Sheet1:
//
2188
//	style, err := f.NewStyle(&excelize.Style{
2189
//	    Fill: excelize.Fill{Type: "gradient", Color: []string{"FFFFFF", "E0EBF5"}, Shading: 1},
2190 2191 2192 2193 2194
//	})
//	if err != nil {
//	    fmt.Println(err)
//	}
//	err = f.SetCellStyle("Sheet1", "H9", "H9", style)
2195 2196 2197
//
// Set solid style pattern fill for cell H9 on Sheet1:
//
2198
//	style, err := f.NewStyle(&excelize.Style{
2199
//	    Fill: excelize.Fill{Type: "pattern", Color: []string{"E0EBF5"}, Pattern: 1},
2200 2201 2202 2203 2204
//	})
//	if err != nil {
//	    fmt.Println(err)
//	}
//	err = f.SetCellStyle("Sheet1", "H9", "H9", style)
2205 2206 2207
//
// Set alignment style for cell H9 on Sheet1:
//
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
//	style, err := f.NewStyle(&excelize.Style{
//	    Alignment: &excelize.Alignment{
//	        Horizontal:      "center",
//	        Indent:          1,
//	        JustifyLastLine: true,
//	        ReadingOrder:    0,
//	        RelativeIndent:  1,
//	        ShrinkToFit:     true,
//	        TextRotation:    45,
//	        Vertical:        "",
//	        WrapText:        true,
//	    },
//	})
//	if err != nil {
//	    fmt.Println(err)
//	}
//	err = f.SetCellStyle("Sheet1", "H9", "H9", style)
2225 2226 2227 2228 2229
//
// Dates and times in Excel are represented by real numbers, for example "Apr 7
// 2017 12:00 PM" is represented by the number 42920.5. Set date and time format
// for cell H9 on Sheet1:
//
2230 2231 2232 2233 2234 2235
//	f.SetCellValue("Sheet1", "H9", 42920.5)
//	style, err := f.NewStyle(&excelize.Style{NumFmt: 22})
//	if err != nil {
//	    fmt.Println(err)
//	}
//	err = f.SetCellStyle("Sheet1", "H9", "H9", style)
2236 2237 2238
//
// Set font style for cell H9 on Sheet1:
//
2239 2240 2241 2242 2243 2244
//	style, err := f.NewStyle(&excelize.Style{
//	    Font: &excelize.Font{
//	        Bold:   true,
//	        Italic: true,
//	        Family: "Times New Roman",
//	        Size:   36,
2245
//	        Color:  "777777",
2246 2247 2248 2249 2250 2251
//	    },
//	})
//	if err != nil {
//	    fmt.Println(err)
//	}
//	err = f.SetCellStyle("Sheet1", "H9", "H9", style)
2252
//
2253 2254
// Hide and lock for cell H9 on Sheet1:
//
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
//	style, err := f.NewStyle(&excelize.Style{
//	    Protection: &excelize.Protection{
//	        Hidden: true,
//	        Locked: true,
//	    },
//	})
//	if err != nil {
//	    fmt.Println(err)
//	}
//	err = f.SetCellStyle("Sheet1", "H9", "H9", style)
2265 2266
func (f *File) SetCellStyle(sheet, hCell, vCell string, styleID int) error {
	hCol, hRow, err := CellNameToCoordinates(hCell)
2267
	if err != nil {
2268
		return err
2269
	}
2270

2271
	vCol, vRow, err := CellNameToCoordinates(vCell)
2272
	if err != nil {
2273
		return err
2274
	}
2275

2276
	// Normalize the range, such correct C1:B3 to B1:C3.
2277 2278
	if vCol < hCol {
		vCol, hCol = hCol, vCol
2279 2280
	}

2281 2282
	if vRow < hRow {
		vRow, hRow = hRow, vRow
2283 2284
	}

2285 2286
	hColIdx := hCol - 1
	hRowIdx := hRow - 1
2287

2288 2289
	vColIdx := vCol - 1
	vRowIdx := vRow - 1
xurime's avatar
xurime 已提交
2290
	f.mu.Lock()
2291
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
2292
	if err != nil {
xurime's avatar
xurime 已提交
2293
		f.mu.Unlock()
xurime's avatar
xurime 已提交
2294 2295
		return err
	}
2296 2297
	s, err := f.stylesReader()
	if err != nil {
xurime's avatar
xurime 已提交
2298
		f.mu.Unlock()
2299 2300
		return err
	}
xurime's avatar
xurime 已提交
2301 2302 2303 2304 2305 2306 2307 2308
	f.mu.Unlock()

	ws.mu.Lock()
	defer ws.mu.Unlock()

	ws.prepareSheetXML(vCol, vRow)
	ws.makeContiguousColumns(hRow, vRow, vCol)

2309 2310 2311 2312
	if styleID < 0 || s.CellXfs == nil || len(s.CellXfs.Xf) <= styleID {
		return newInvalidStyleID(styleID)
	}

2313 2314
	for r := hRowIdx; r <= vRowIdx; r++ {
		for k := hColIdx; k <= vColIdx; k++ {
2315
			ws.SheetData.Row[r].C[k].S = styleID
2316 2317
		}
	}
xurime's avatar
xurime 已提交
2318
	return err
2319
}
2320

xurime's avatar
xurime 已提交
2321 2322 2323 2324
// SetConditionalFormat provides a function to create conditional formatting
// rule for cell value. Conditional formatting is a feature of Excel which
// allows you to apply a format to a cell or a range of cells based on certain
// criteria.
2325 2326 2327 2328
//
// The type option is a required parameter and it has no default value.
// Allowable type values and their associated parameters are:
//
2329 2330
//	 Type          | Parameters
//	---------------+------------------------------------
2331 2332
//	 cell          | Criteria
//	               | Value
2333 2334
//	               | MinValue
//	               | MaxValue
2335 2336 2337 2338
//	 time_period   | Criteria
//	 text          | Criteria
//	               | Value
//	 average       | Criteria
2339 2340
//	 duplicate     | (none)
//	 unique        | (none)
2341 2342 2343 2344
//	 top           | Criteria
//	               | Value
//	 bottom        | Criteria
//	               | Value
2345 2346 2347 2348
//	 blanks        | (none)
//	 no_blanks     | (none)
//	 errors        | (none)
//	 no_errors     | (none)
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
//	 2_color_scale | MinType
//	               | MaxType
//	               | MinValue
//	               | MaxValue
//	               | MinColor
//	               | MaxColor
//	 3_color_scale | MinType
//	               | MidType
//	               | MaxType
//	               | MinValue
//	               | MidValue
//	               | MaxValue
//	               | MinColor
//	               | MidColor
//	               | MaxColor
//	 data_bar      | MinType
//	               | MaxType
//	               | MinValue
//	               | MaxValue
2368
//	               | BarBorderColor
2369
//	               | BarColor
2370 2371 2372
//	               | BarDirection
//	               | BarOnly
//	               | BarSolid
2373
//	 icon_set      | IconStyle
2374 2375
//	               | ReverseIcons
//	               | IconsOnly
2376 2377 2378
//	 formula       | Criteria
//
// The 'Criteria' parameter is used to set the criteria by which the cell data
2379
// will be evaluated. It has no default value. The most common criteria as
xurime's avatar
xurime 已提交
2380
// applied to {Type: "cell"} are:
2381
//
2382 2383 2384 2385 2386 2387 2388 2389
//	between                  |
//	not between              |
//	equal to                 | ==
//	not equal to             | !=
//	greater than             | >
//	less than                | <
//	greater than or equal to | >=
//	less than or equal to    | <=
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
//
// You can either use Excel's textual description strings, in the first column
// above, or the more common symbolic alternatives.
//
// Additional criteria which are specific to other conditional format types are
// shown in the relevant sections below.
//
// value: The value is generally used along with the criteria parameter to set
// the rule by which the cell data will be evaluated:
//
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
//	err := f.SetConditionalFormat("Sheet1", "D1:D10",
//	    []excelize.ConditionalFormatOptions{
//	        {
//	            Type:     "cell",
//	            Criteria: ">",
//	            Format:   format,
//	            Value:    "6",
//	        },
//	    },
//	)
2410 2411 2412
//
// The value property can also be an cell reference:
//
2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
//	err := f.SetConditionalFormat("Sheet1", "D1:D10",
//	    []excelize.ConditionalFormatOptions{
//	        {
//	            Type:     "cell",
//	            Criteria: ">",
//	            Format:   format,
//	            Value:    "$C$1",
//	        },
//	    },
//	)
2423 2424 2425
//
// type: format - The format parameter is used to specify the format that will
// be applied to the cell when the conditional formatting criterion is met. The
2426
// format is created using the NewConditionalStyle function in the same way as
2427 2428
// cell formats:
//
2429 2430
//	format, err := f.NewConditionalStyle(
//	    &excelize.Style{
2431
//	        Font: &excelize.Font{Color: "9A0511"},
2432
//	        Fill: excelize.Fill{
2433
//	            Type: "pattern", Color: []string{"FEC7CE"}, Pattern: 1,
2434 2435 2436
//	        },
//	    },
//	)
2437 2438 2439
//	if err != nil {
//	    fmt.Println(err)
//	}
2440 2441 2442 2443 2444
//	err = f.SetConditionalFormat("Sheet1", "D1:D10",
//	    []excelize.ConditionalFormatOptions{
//	        {Type: "cell", Criteria: ">", Format: format, Value: "6"},
//	    },
//	)
2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
//
// Note: In Excel, a conditional format is superimposed over the existing cell
// format and not all cell format properties can be modified. Properties that
// cannot be modified in a conditional format are font name, font size,
// superscript and subscript, diagonal borders, all alignment properties and all
// protection properties.
//
// Excel specifies some default formats to be used with conditional formatting.
// These can be replicated using the following excelize formats:
//
2455
//	// Rose format for bad conditional.
2456 2457
//	format1, err := f.NewConditionalStyle(
//	    &excelize.Style{
2458
//	        Font: &excelize.Font{Color: "9A0511"},
2459 2460 2461 2462 2463
//	        Fill: excelize.Fill{
//	            Type: "pattern", Color: []string{"#FEC7CE"}, Pattern: 1,
//	        },
//	    },
//	)
2464
//
2465
//	// Light yellow format for neutral conditional.
2466 2467
//	format2, err := f.NewConditionalStyle(
//	    &excelize.Style{
2468
//	        Font: &excelize.Font{Color: "9B5713"},
2469
//	        Fill: excelize.Fill{
2470
//	            Type: "pattern", Color: []string{"FEEAA0"}, Pattern: 1,
2471 2472 2473
//	        },
//	    },
//	)
2474
//
2475
//	// Light green format for good conditional.
2476 2477
//	format3, err := f.NewConditionalStyle(
//	    &excelize.Style{
2478
//	        Font: &excelize.Font{Color: "09600B"},
2479
//	        Fill: excelize.Fill{
2480
//	            Type: "pattern", Color: []string{"C7EECF"}, Pattern: 1,
2481 2482 2483
//	        },
//	    },
//	)
2484
//
2485
// type: MinValue - The 'MinValue' parameter is used to set the lower limiting
xurime's avatar
xurime 已提交
2486
// value when the criteria is either "between" or "not between".
2487
//
2488
//	// Highlight cells rules: between...
2489 2490 2491 2492 2493 2494
//	err := f.SetConditionalFormat("Sheet1", "A1:A10",
//	    []excelize.ConditionalFormatOptions{
//	        {
//	            Type:     "cell",
//	            Criteria: "between",
//	            Format:   format,
2495 2496
//	            MinValue: 6",
//	            MaxValue: 8",
2497 2498 2499
//	        },
//	    },
//	)
2500
//
2501
// type: MaxValue - The 'MaxValue' parameter is used to set the upper limiting
xurime's avatar
xurime 已提交
2502 2503
// value when the criteria is either "between" or "not between". See the
// previous example.
2504 2505 2506 2507
//
// type: average - The average type is used to specify Excel's "Average" style
// conditional format:
//
2508
//	// Top/Bottom rules: Above Average...
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518
//	err := f.SetConditionalFormat("Sheet1", "A1:A10",
//	    []excelize.ConditionalFormatOptions{
//	        {
//	            Type:         "average",
//	            Criteria:     "=",
//	            Format:       format1,
//	            AboveAverage: true,
//	        },
//	    },
//	)
2519
//
2520
//	// Top/Bottom rules: Below Average...
2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
//	err := f.SetConditionalFormat("Sheet1", "B1:B10",
//	    []excelize.ConditionalFormatOptions{
//	        {
//	            Type:         "average",
//	            Criteria:     "=",
//	            Format:       format2,
//	            AboveAverage: false,
//	        },
//	    },
//	)
2531
//
2532 2533
// type: duplicate - The duplicate type is used to highlight duplicate cells in
// a range:
2534
//
2535
//	// Highlight cells rules: Duplicate Values...
2536 2537 2538 2539 2540
//	err := f.SetConditionalFormat("Sheet1", "A1:A10",
//	    []excelize.ConditionalFormatOptions{
//	        {Type: "duplicate", Criteria: "=", Format: format},
//	    },
//	)
2541 2542 2543
//
// type: unique - The unique type is used to highlight unique cells in a range:
//
2544
//	// Highlight cells rules: Not Equal To...
2545 2546 2547 2548 2549
//	err := f.SetConditionalFormat("Sheet1", "A1:A10",
//	    []excelize.ConditionalFormatOptions{
//	        {Type: "unique", Criteria: "=", Format: format},
//	    },
//	)
2550
//
2551 2552
// type: top - The top type is used to specify the top n values by number or
// percentage in a range:
2553
//
2554
//	// Top/Bottom rules: Top 10.
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
//	err := f.SetConditionalFormat("Sheet1", "H1:H10",
//	    []excelize.ConditionalFormatOptions{
//	        {
//	            Type:     "top",
//	            Criteria: "=",
//	            Format:   format,
//	            Value:    "6",
//	        },
//	    },
//	)
2565 2566 2567
//
// The criteria can be used to indicate that a percentage condition is required:
//
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
//	err := f.SetConditionalFormat("Sheet1", "A1:A10",
//	    []excelize.ConditionalFormatOptions{
//	        {
//	            Type:     "top",
//	            Criteria: "=",
//	            Format:   format,
//	            Value:    "6",
//	            Percent:  true,
//	        },
//	    },
//	)
2579 2580 2581 2582
//
// type: 2_color_scale - The 2_color_scale type is used to specify Excel's "2
// Color Scale" style conditional format:
//
2583
//	// Color scales: 2 color.
2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595
//	err := f.SetConditionalFormat("Sheet1", "A1:A10",
//	    []excelize.ConditionalFormatOptions{
//	        {
//	            Type:     "2_color_scale",
//	            Criteria: "=",
//	            MinType:  "min",
//	            MaxType:  "max",
//	            MinColor: "#F8696B",
//	            MaxColor: "#63BE7B",
//	        },
//	    },
//	)
2596
//
2597 2598
// This conditional type can be modified with MinType, MaxType, MinValue,
// MaxValue, MinColor and MaxColor, see below.
2599 2600 2601 2602
//
// type: 3_color_scale - The 3_color_scale type is used to specify Excel's "3
// Color Scale" style conditional format:
//
2603
//	// Color scales: 3 color.
2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
//	err := f.SetConditionalFormat("Sheet1", "A1:A10",
//	    []excelize.ConditionalFormatOptions{
//	        {
//	            Type:     "3_color_scale",
//	            Criteria: "=",
//	            MinType:  "min",
//	            MidType:  "percentile",
//	            MaxType:  "max",
//	            MinColor: "#F8696B",
//	            MidColor: "#FFEB84",
//	            MaxColor: "#63BE7B",
//	        },
//	    },
//	)
2618
//
2619 2620
// This conditional type can be modified with MinType, MidType, MaxType,
// MinValue, MidValue, MaxValue, MinColor, MidColor and MaxColor, see
2621 2622 2623 2624 2625
// below.
//
// type: data_bar - The data_bar type is used to specify Excel's "Data Bar"
// style conditional format.
//
2626 2627 2628 2629
// MinType - The MinType and MaxType properties are available when the
// conditional formatting type is 2_color_scale, 3_color_scale or data_bar.
// The MidType is available for 3_color_scale. The properties are used as
// follows:
2630
//
2631
//	// Data Bars: Gradient Fill.
2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
//	err := f.SetConditionalFormat("Sheet1", "K1:K10",
//	    []excelize.ConditionalFormatOptions{
//	        {
//	            Type:     "data_bar",
//	            Criteria: "=",
//	            MinType:  "min",
//	            MaxType:  "max",
//	            BarColor: "#638EC6",
//	        },
//	    },
//	)
2643 2644 2645
//
// The available min/mid/max types are:
//
2646
//	min        (for MinType only)
2647 2648 2649 2650
//	num
//	percent
//	percentile
//	formula
2651
//	max        (for MaxType only)
2652
//
2653
// MidType - Used for 3_color_scale. Same as MinType, see above.
2654
//
2655
// MaxType - Same as MinType, see above.
2656
//
2657 2658
// MinValue - The MinValue and MaxValue properties are available when the
// conditional formatting type is 2_color_scale, 3_color_scale or data_bar.
2659
//
2660 2661
// MidValue - The MidValue is available for 3_color_scale. Same as MinValue,
// see above.
2662
//
2663
// MaxValue - Same as MinValue, see above.
2664
//
2665
// MinColor - The MinColor and MaxColor properties are available when the
2666 2667
// conditional formatting type is 2_color_scale, 3_color_scale or data_bar.
//
2668 2669
// MidColor - The MidColor is available for 3_color_scale. The properties
// are used as follows:
2670
//
2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
//	// Color scales: 3 color.
//	err := f.SetConditionalFormat("Sheet1", "B1:B10",
//	    []excelize.ConditionalFormatOptions{
//	        {
//	            Type:     "3_color_scale",
//	            Criteria: "=",
//	            MinType:  "min",
//	            MidType:  "percentile",
//	            MaxType:  "max",
//	            MinColor: "#F8696B",
//	            MidColor: "#FFEB84",
//	            MaxColor: "#63BE7B",
//	        },
//	    },
//	)
2686
//
2687
// MaxColor - Same as MinColor, see above.
2688
//
2689
// BarColor - Used for data_bar. Same as MinColor, see above.
xurime's avatar
xurime 已提交
2690 2691 2692 2693
//
// BarBorderColor - Used for sets the color for the border line of a data bar,
// this is only visible in Excel 2010 and later.
//
2694 2695 2696 2697 2698 2699 2700
// BarDirection - sets the direction for data bars. The available options are:
//
//	context - Data bar direction is set by spreadsheet application based on the context of the data displayed.
//	leftToRight - Data bar direction is from right to left.
//	rightToLeft - Data bar direction is from left to right.
//
// BarOnly - Used for set displays a bar data but not the data in the cells.
xurime's avatar
xurime 已提交
2701 2702 2703 2704
//
// BarSolid - Used for turns on a solid (non-gradient) fill for data bars, this
// is only visible in Excel 2010 and later.
//
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728
// IconStyle - The available options are:
//
//	3Arrows
//	3ArrowsGray
//	3Flags
//	3Signs
//	3Symbols
//	3Symbols2
//	3TrafficLights1
//	3TrafficLights2
//	4Arrows
//	4ArrowsGray
//	4Rating
//	4RedToBlack
//	4TrafficLights
//	5Arrows
//	5ArrowsGray
//	5Quarters
//	5Rating
//
// ReverseIcons - Used for set reversed icons sets.
//
// IconsOnly - Used for set displayed without the cell value.
//
xurime's avatar
xurime 已提交
2729 2730 2731 2732
// StopIfTrue - used to set the "stop if true" feature of a conditional
// formatting rule when more than one rule is applied to a cell or a range of
// cells. When this parameter is set then subsequent rules are not evaluated
// if the current rule is true.
xurime's avatar
xurime 已提交
2733
func (f *File) SetConditionalFormat(sheet, rangeRef string, opts []ConditionalFormatOptions) error {
2734
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
2735 2736 2737
	if err != nil {
		return err
	}
2738 2739 2740 2741 2742 2743 2744 2745
	if strings.Contains(rangeRef, ":") {
		rect, err := rangeRefToCoordinates(rangeRef)
		if err != nil {
			return err
		}
		_ = sortCoordinates(rect)
		rangeRef, _ = f.coordinatesToRangeRef(rect, strings.Contains(rangeRef, "$"))
	}
xurime's avatar
xurime 已提交
2746 2747 2748 2749 2750
	// Create a pseudo GUID for each unique rule.
	var rules int
	for _, cf := range ws.ConditionalFormatting {
		rules += len(cf.CfRule)
	}
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
	var (
		cfRule          []*xlsxCfRule
		noCriteriaTypes = []string{
			"containsBlanks",
			"notContainsBlanks",
			"containsErrors",
			"notContainsErrors",
			"expression",
			"iconSet",
		}
	)
2762
	for p, v := range opts {
2763 2764 2765 2766 2767
		var vt, ct string
		var ok bool
		// "type" is a required parameter, check for valid validation types.
		vt, ok = validType[v.Type]
		if ok {
xurime's avatar
xurime 已提交
2768 2769
			// Check for valid criteria types.
			ct, ok = criteriaType[v.Criteria]
2770
			if ok || inStrSlice(noCriteriaTypes, vt, true) != -1 {
2771
				drawFunc, ok := drawContFmtFunc[vt]
xurime's avatar
xurime 已提交
2772
				if ok {
2773 2774
					rule, x14rule := drawFunc(p, ct, strings.Split(rangeRef, ":")[0],
						fmt.Sprintf("{00000000-0000-0000-%04X-%012X}", f.getSheetID(sheet), rules+p), &v)
2775 2776 2777
					if rule == nil {
						return ErrParameterInvalid
					}
xurime's avatar
xurime 已提交
2778 2779 2780 2781 2782 2783 2784
					if x14rule != nil {
						if err = f.appendCfRule(ws, x14rule); err != nil {
							return err
						}
						f.addSheetNameSpace(sheet, NameSpaceSpreadSheetX14)
					}
					cfRule = append(cfRule, rule)
2785
					continue
xurime's avatar
xurime 已提交
2786 2787
				}
			}
2788
			return ErrParameterInvalid
2789
		}
2790
		return ErrParameterInvalid
2791 2792
	}

2793
	ws.ConditionalFormatting = append(ws.ConditionalFormatting, &xlsxConditionalFormatting{
xurime's avatar
xurime 已提交
2794
		SQRef:  rangeRef,
2795 2796
		CfRule: cfRule,
	})
2797
	return err
2798 2799
}

xurime's avatar
xurime 已提交
2800 2801 2802
// appendCfRule provides a function to append rules to conditional formatting.
func (f *File) appendCfRule(ws *xlsxWorksheet, rule *xlsxX14CfRule) error {
	var (
2803 2804 2805
		err                                      error
		idx                                      int
		appendMode                               bool
2806
		decodeExtLst                             = new(decodeExtLst)
2807 2808
		condFmts                                 *xlsxX14ConditionalFormattings
		decodeCondFmts                           *decodeX14ConditionalFormattings
2809
		ext                                      *xlsxExt
2810
		condFmtBytes, condFmtsBytes, extLstBytes []byte
xurime's avatar
xurime 已提交
2811
	)
2812 2813 2814
	condFmtBytes, _ = xml.Marshal([]*xlsxX14ConditionalFormatting{
		{XMLNSXM: NameSpaceSpreadSheetExcel2006Main.Value, CfRule: []*xlsxX14CfRule{rule}},
	})
xurime's avatar
xurime 已提交
2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829
	if ws.ExtLst != nil { // append mode ext
		if err = f.xmlNewDecoder(strings.NewReader("<extLst>" + ws.ExtLst.Ext + "</extLst>")).
			Decode(decodeExtLst); err != nil && err != io.EOF {
			return err
		}
		for idx, ext = range decodeExtLst.Ext {
			if ext.URI == ExtURIConditionalFormattings {
				decodeCondFmts = new(decodeX14ConditionalFormattings)
				_ = f.xmlNewDecoder(strings.NewReader(ext.Content)).Decode(decodeCondFmts)
				if condFmts == nil {
					condFmts = &xlsxX14ConditionalFormattings{}
				}
				condFmts.Content = decodeCondFmts.Content + string(condFmtBytes)
				condFmtsBytes, _ = xml.Marshal(condFmts)
				decodeExtLst.Ext[idx].Content = string(condFmtsBytes)
2830
				appendMode = true
xurime's avatar
xurime 已提交
2831 2832 2833
			}
		}
	}
2834 2835
	if !appendMode {
		condFmtsBytes, _ = xml.Marshal(&xlsxX14ConditionalFormattings{Content: string(condFmtBytes)})
2836
		decodeExtLst.Ext = append(decodeExtLst.Ext, &xlsxExt{
2837 2838 2839 2840
			URI: ExtURIConditionalFormattings, Content: string(condFmtsBytes),
		})
	}
	sort.Slice(decodeExtLst.Ext, func(i, j int) bool {
2841 2842
		return inStrSlice(worksheetExtURIPriority, decodeExtLst.Ext[i].URI, false) <
			inStrSlice(worksheetExtURIPriority, decodeExtLst.Ext[j].URI, false)
xurime's avatar
xurime 已提交
2843
	})
2844 2845
	extLstBytes, err = xml.Marshal(decodeExtLst)
	ws.ExtLst = &xlsxExtLst{Ext: strings.TrimSuffix(strings.TrimPrefix(string(extLstBytes), "<extLst>"), "</extLst>")}
xurime's avatar
xurime 已提交
2846 2847 2848
	return err
}

2849 2850 2851
// extractCondFmtCellIs provides a function to extract conditional format
// settings for cell value (include between, not between, equal, not equal,
// greater than and less than) by given conditional formatting rule.
2852
func (f *File) extractCondFmtCellIs(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
2853 2854 2855 2856
	format := ConditionalFormatOptions{StopIfTrue: c.StopIfTrue, Type: "cell", Criteria: operatorType[c.Operator]}
	if c.DxfID != nil {
		format.Format = *c.DxfID
	}
2857
	if len(c.Formula) == 2 {
2858
		format.MinValue, format.MaxValue = c.Formula[0], c.Formula[1]
2859
		return format
2860 2861
	}
	format.Value = c.Formula[0]
2862
	return format
2863 2864
}

2865 2866
// extractCondFmtTimePeriod provides a function to extract conditional format
// settings for time period by given conditional formatting rule.
2867
func (f *File) extractCondFmtTimePeriod(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
2868 2869 2870 2871 2872
	format := ConditionalFormatOptions{StopIfTrue: c.StopIfTrue, Type: "time_period", Criteria: operatorType[c.Operator]}
	if c.DxfID != nil {
		format.Format = *c.DxfID
	}
	return format
2873 2874
}

2875 2876
// extractCondFmtText provides a function to extract conditional format
// settings for text cell values by given conditional formatting rule.
2877
func (f *File) extractCondFmtText(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
2878 2879 2880 2881 2882
	format := ConditionalFormatOptions{StopIfTrue: c.StopIfTrue, Type: "text", Criteria: operatorType[c.Operator], Value: c.Text}
	if c.DxfID != nil {
		format.Format = *c.DxfID
	}
	return format
2883 2884
}

2885 2886 2887
// extractCondFmtTop10 provides a function to extract conditional format
// settings for top N (default is top 10) by given conditional formatting
// rule.
2888
func (f *File) extractCondFmtTop10(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
2889
	format := ConditionalFormatOptions{
xurime's avatar
xurime 已提交
2890 2891 2892 2893 2894
		StopIfTrue: c.StopIfTrue,
		Type:       "top",
		Criteria:   "=",
		Percent:    c.Percent,
		Value:      strconv.Itoa(c.Rank),
2895
	}
2896 2897 2898
	if c.DxfID != nil {
		format.Format = *c.DxfID
	}
2899 2900 2901
	if c.Bottom {
		format.Type = "bottom"
	}
2902
	return format
2903 2904 2905 2906 2907
}

// extractCondFmtAboveAverage provides a function to extract conditional format
// settings for above average and below average by given conditional formatting
// rule.
2908
func (f *File) extractCondFmtAboveAverage(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
2909 2910 2911 2912 2913 2914 2915
	format := ConditionalFormatOptions{
		StopIfTrue: c.StopIfTrue,
		Type:       "average",
		Criteria:   "=",
	}
	if c.DxfID != nil {
		format.Format = *c.DxfID
2916
	}
2917 2918 2919 2920
	if c.AboveAverage != nil {
		format.AboveAverage = *c.AboveAverage
	}
	return format
2921 2922 2923 2924 2925
}

// extractCondFmtDuplicateUniqueValues provides a function to extract
// conditional format settings for duplicate and unique values by given
// conditional formatting rule.
2926
func (f *File) extractCondFmtDuplicateUniqueValues(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
2927
	format := ConditionalFormatOptions{
xurime's avatar
xurime 已提交
2928
		StopIfTrue: c.StopIfTrue,
2929 2930 2931 2932 2933 2934
		Type: map[string]string{
			"duplicateValues": "duplicate",
			"uniqueValues":    "unique",
		}[c.Type],
		Criteria: "=",
	}
2935 2936 2937 2938
	if c.DxfID != nil {
		format.Format = *c.DxfID
	}
	return format
2939 2940
}

2941 2942
// extractCondFmtBlanks provides a function to extract conditional format
// settings for blank cells by given conditional formatting rule.
2943
func (f *File) extractCondFmtBlanks(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
2944
	format := ConditionalFormatOptions{
2945 2946 2947
		StopIfTrue: c.StopIfTrue,
		Type:       "blanks",
	}
2948 2949 2950 2951
	if c.DxfID != nil {
		format.Format = *c.DxfID
	}
	return format
2952 2953 2954 2955
}

// extractCondFmtNoBlanks provides a function to extract conditional format
// settings for no blank cells by given conditional formatting rule.
2956
func (f *File) extractCondFmtNoBlanks(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
2957
	format := ConditionalFormatOptions{
2958 2959 2960
		StopIfTrue: c.StopIfTrue,
		Type:       "no_blanks",
	}
2961 2962 2963 2964
	if c.DxfID != nil {
		format.Format = *c.DxfID
	}
	return format
2965 2966 2967 2968
}

// extractCondFmtErrors provides a function to extract conditional format
// settings for cells with errors by given conditional formatting rule.
2969
func (f *File) extractCondFmtErrors(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
2970
	format := ConditionalFormatOptions{
2971 2972 2973
		StopIfTrue: c.StopIfTrue,
		Type:       "errors",
	}
2974 2975 2976 2977
	if c.DxfID != nil {
		format.Format = *c.DxfID
	}
	return format
2978 2979 2980 2981
}

// extractCondFmtNoErrors provides a function to extract conditional format
// settings for cells without errors by given conditional formatting rule.
2982
func (f *File) extractCondFmtNoErrors(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
2983
	format := ConditionalFormatOptions{
2984 2985 2986
		StopIfTrue: c.StopIfTrue,
		Type:       "no_errors",
	}
2987 2988 2989 2990
	if c.DxfID != nil {
		format.Format = *c.DxfID
	}
	return format
2991 2992
}

2993 2994 2995
// extractCondFmtColorScale provides a function to extract conditional format
// settings for color scale (include 2 color scale and 3 color scale) by given
// conditional formatting rule.
2996
func (f *File) extractCondFmtColorScale(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
xurime's avatar
xurime 已提交
2997
	format := ConditionalFormatOptions{StopIfTrue: c.StopIfTrue}
2998 2999 3000 3001 3002 3003 3004 3005
	format.Type, format.Criteria = "2_color_scale", "="
	values := len(c.ColorScale.Cfvo)
	colors := len(c.ColorScale.Color)
	if colors > 1 && values > 1 {
		format.MinType = c.ColorScale.Cfvo[0].Type
		if c.ColorScale.Cfvo[0].Val != "0" {
			format.MinValue = c.ColorScale.Cfvo[0].Val
		}
3006
		format.MinColor = "#" + f.getThemeColor(c.ColorScale.Color[0])
3007 3008 3009 3010
		format.MaxType = c.ColorScale.Cfvo[1].Type
		if c.ColorScale.Cfvo[1].Val != "0" {
			format.MaxValue = c.ColorScale.Cfvo[1].Val
		}
3011
		format.MaxColor = "#" + f.getThemeColor(c.ColorScale.Color[1])
3012 3013 3014 3015 3016 3017 3018
	}
	if colors == 3 {
		format.Type = "3_color_scale"
		format.MidType = c.ColorScale.Cfvo[1].Type
		if c.ColorScale.Cfvo[1].Val != "0" {
			format.MidValue = c.ColorScale.Cfvo[1].Val
		}
3019
		format.MidColor = "#" + f.getThemeColor(c.ColorScale.Color[1])
3020 3021 3022 3023
		format.MaxType = c.ColorScale.Cfvo[2].Type
		if c.ColorScale.Cfvo[2].Val != "0" {
			format.MaxValue = c.ColorScale.Cfvo[2].Val
		}
3024
		format.MaxColor = "#" + f.getThemeColor(c.ColorScale.Color[2])
3025
	}
3026
	return format
3027 3028
}

3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046
// extractCondFmtDataBarRule provides a function to extract conditional format
// settings for data bar by given conditional formatting rule extension list.
func (f *File) extractCondFmtDataBarRule(ID string, format *ConditionalFormatOptions, condFmts []decodeX14ConditionalFormatting) {
	for _, condFmt := range condFmts {
		for _, rule := range condFmt.CfRule {
			if rule.DataBar != nil && rule.ID == ID {
				format.BarDirection = rule.DataBar.Direction
				if rule.DataBar.Gradient != nil && !*rule.DataBar.Gradient {
					format.BarSolid = true
				}
				if rule.DataBar.BorderColor != nil {
					format.BarBorderColor = "#" + f.getThemeColor(rule.DataBar.BorderColor)
				}
			}
		}
	}
}

3047 3048
// extractCondFmtDataBar provides a function to extract conditional format
// settings for data bar by given conditional formatting rule.
3049
func (f *File) extractCondFmtDataBar(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
3050
	format := ConditionalFormatOptions{Type: "data_bar", Criteria: "="}
3051
	if c.DataBar != nil {
xurime's avatar
xurime 已提交
3052
		format.StopIfTrue = c.StopIfTrue
3053
		format.MinType = c.DataBar.Cfvo[0].Type
3054
		format.MinValue = c.DataBar.Cfvo[0].Val
3055
		format.MaxType = c.DataBar.Cfvo[1].Type
3056
		format.MaxValue = c.DataBar.Cfvo[1].Val
3057
		format.BarColor = "#" + f.getThemeColor(c.DataBar.Color[0])
xurime's avatar
xurime 已提交
3058 3059 3060 3061
		if c.DataBar.ShowValue != nil {
			format.BarOnly = !*c.DataBar.ShowValue
		}
	}
3062
	extractExtLst := func(ID string, extLst *decodeExtLst) {
xurime's avatar
xurime 已提交
3063 3064
		for _, ext := range extLst.Ext {
			if ext.URI == ExtURIConditionalFormattings {
3065
				decodeCondFmts := new(decodeX14ConditionalFormattingRules)
xurime's avatar
xurime 已提交
3066
				if err := xml.Unmarshal([]byte(ext.Content), &decodeCondFmts); err == nil {
3067
					f.extractCondFmtDataBarRule(ID, &format, decodeCondFmts.CondFmt)
xurime's avatar
xurime 已提交
3068 3069 3070 3071 3072 3073 3074
				}
			}
		}
	}
	if c.ExtLst != nil {
		ext := decodeX14ConditionalFormattingExt{}
		if err := xml.Unmarshal([]byte(c.ExtLst.Ext), &ext); err == nil && extLst != nil {
3075
			decodeExtLst := new(decodeExtLst)
xurime's avatar
xurime 已提交
3076
			if err = xml.Unmarshal([]byte("<extLst>"+extLst.Ext+"</extLst>"), decodeExtLst); err == nil {
3077
				extractExtLst(ext.ID, decodeExtLst)
xurime's avatar
xurime 已提交
3078 3079
			}
		}
3080
	}
3081
	return format
3082 3083 3084 3085
}

// extractCondFmtExp provides a function to extract conditional format settings
// for expression by given conditional formatting rule.
3086
func (f *File) extractCondFmtExp(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
3087 3088 3089 3090
	format := ConditionalFormatOptions{StopIfTrue: c.StopIfTrue, Type: "formula"}
	if c.DxfID != nil {
		format.Format = *c.DxfID
	}
3091 3092 3093
	if len(c.Formula) > 0 {
		format.Criteria = c.Formula[0]
	}
3094
	return format
3095 3096
}

3097 3098
// extractCondFmtIconSet provides a function to extract conditional format
// settings for icon sets by given conditional formatting rule.
3099
func (f *File) extractCondFmtIconSet(c *xlsxCfRule, extLst *xlsxExtLst) ConditionalFormatOptions {
3100
	format := ConditionalFormatOptions{Type: "icon_set"}
3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
	if c.IconSet != nil {
		if c.IconSet.ShowValue != nil {
			format.IconsOnly = !*c.IconSet.ShowValue
		}
		format.IconStyle = c.IconSet.IconSet
		format.ReverseIcons = c.IconSet.Reverse
	}
	return format
}

3111 3112
// GetConditionalFormats returns conditional format settings by given worksheet
// name.
3113 3114
func (f *File) GetConditionalFormats(sheet string) (map[string][]ConditionalFormatOptions, error) {
	conditionalFormats := make(map[string][]ConditionalFormatOptions)
3115 3116 3117 3118 3119
	ws, err := f.workSheetReader(sheet)
	if err != nil {
		return conditionalFormats, err
	}
	for _, cf := range ws.ConditionalFormatting {
3120
		var opts []ConditionalFormatOptions
3121 3122
		for _, cr := range cf.CfRule {
			if extractFunc, ok := extractContFmtFunc[cr.Type]; ok {
3123
				opts = append(opts, extractFunc(f, cr, ws.ExtLst))
3124 3125
			}
		}
3126
		conditionalFormats[cf.SQRef] = opts
3127 3128 3129 3130
	}
	return conditionalFormats, err
}

3131
// UnsetConditionalFormat provides a function to unset the conditional format
3132
// by given worksheet name and range reference.
xurime's avatar
xurime 已提交
3133
func (f *File) UnsetConditionalFormat(sheet, rangeRef string) error {
3134 3135 3136 3137 3138
	ws, err := f.workSheetReader(sheet)
	if err != nil {
		return err
	}
	for i, cf := range ws.ConditionalFormatting {
xurime's avatar
xurime 已提交
3139
		if cf.SQRef == rangeRef {
3140 3141 3142 3143 3144 3145 3146
			ws.ConditionalFormatting = append(ws.ConditionalFormatting[:i], ws.ConditionalFormatting[i+1:]...)
			return nil
		}
	}
	return nil
}

xurime's avatar
xurime 已提交
3147 3148 3149
// drawCondFmtCellIs provides a function to create conditional formatting rule
// for cell value (include between, not between, equal, not equal, greater
// than and less than) by given priority, criteria type and format settings.
3150
func drawCondFmtCellIs(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
3151
	c := &xlsxCfRule{
xurime's avatar
xurime 已提交
3152 3153 3154 3155
		Priority:   p + 1,
		StopIfTrue: format.StopIfTrue,
		Type:       validType[format.Type],
		Operator:   ct,
3156
		DxfID:      intPtr(format.Format),
3157 3158
	}
	// "between" and "not between" criteria require 2 values.
3159
	if ct == "between" || ct == "notBetween" {
3160
		c.Formula = append(c.Formula, []string{format.MinValue, format.MaxValue}...)
3161
	}
3162
	if inStrSlice(cellIsCriteriaType, ct, true) != -1 {
3163 3164
		c.Formula = append(c.Formula, format.Value)
	}
xurime's avatar
xurime 已提交
3165
	return c, nil
3166 3167
}

3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193
// drawCondFmtTimePeriod provides a function to create conditional formatting
// rule for time period by given priority, criteria type and format settings.
func drawCondFmtTimePeriod(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
	return &xlsxCfRule{
		Priority:   p + 1,
		StopIfTrue: format.StopIfTrue,
		Type:       "timePeriod",
		Operator:   ct,
		Formula: []string{
			map[string]string{
				"yesterday":      fmt.Sprintf("FLOOR(%s,1)=TODAY()-1", ref),
				"today":          fmt.Sprintf("FLOOR(%s,1)=TODAY()", ref),
				"tomorrow":       fmt.Sprintf("FLOOR(%s,1)=TODAY()+1", ref),
				"last 7 days":    fmt.Sprintf("AND(TODAY()-FLOOR(%[1]s,1)<=6,FLOOR(%[1]s,1)<=TODAY())", ref),
				"last week":      fmt.Sprintf("AND(TODAY()-ROUNDDOWN(%[1]s,0)>=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN(%[1]s,0)<(WEEKDAY(TODAY())+7))", ref),
				"this week":      fmt.Sprintf("AND(TODAY()-ROUNDDOWN(%[1]s,0)<=WEEKDAY(TODAY())-1,ROUNDDOWN(%[1]s,0)-TODAY()>=7-WEEKDAY(TODAY()))", ref),
				"continue week":  fmt.Sprintf("AND(ROUNDDOWN(%[1]s,0)-TODAY()>(7-WEEKDAY(TODAY())),ROUNDDOWN(%[1]s,0)-TODAY()<(15-WEEKDAY(TODAY())))", ref),
				"last month":     fmt.Sprintf("AND(MONTH(%[1]s)=MONTH(TODAY())-1,OR(YEAR(%[1]s)=YEAR(TODAY()),AND(MONTH(%[1]s)=1,YEAR(%[1]s)=YEAR(TODAY())-1)))", ref),
				"this month":     fmt.Sprintf("AND(MONTH(%[1]s)=MONTH(TODAY()),YEAR(%[1]s)=YEAR(TODAY()))", ref),
				"continue month": fmt.Sprintf("AND(MONTH(%[1]s)=MONTH(TODAY())+1,OR(YEAR(%[1]s)=YEAR(TODAY()),AND(MONTH(%[1]s)=12,YEAR(%[1]s)=YEAR(TODAY())+1)))", ref),
			}[ct],
		},
		DxfID: intPtr(format.Format),
	}, nil
}

3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223
// drawCondFmtText provides a function to create conditional formatting rule for
// text cell values by given priority, criteria type and format settings.
func drawCondFmtText(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
	return &xlsxCfRule{
		Priority:   p + 1,
		StopIfTrue: format.StopIfTrue,
		Type: map[string]string{
			"containsText": "containsText",
			"notContains":  "notContainsText",
			"beginsWith":   "beginsWith",
			"endsWith":     "endsWith",
		}[ct],
		Text:     format.Value,
		Operator: ct,
		Formula: []string{
			map[string]string{
				"containsText": fmt.Sprintf("NOT(ISERROR(SEARCH(\"%s\",%s)))",
					strings.NewReplacer(`"`, `""`).Replace(format.Value), ref),
				"notContains": fmt.Sprintf("ISERROR(SEARCH(\"%s\",%s))",
					strings.NewReplacer(`"`, `""`).Replace(format.Value), ref),
				"beginsWith": fmt.Sprintf("LEFT(%[2]s,LEN(\"%[1]s\"))=\"%[1]s\"",
					strings.NewReplacer(`"`, `""`).Replace(format.Value), ref),
				"endsWith": fmt.Sprintf("RIGHT(%[2]s,LEN(\"%[1]s\"))=\"%[1]s\"",
					strings.NewReplacer(`"`, `""`).Replace(format.Value), ref),
			}[ct],
		},
		DxfID: intPtr(format.Format),
	}, nil
}

xurime's avatar
xurime 已提交
3224 3225
// drawCondFmtTop10 provides a function to create conditional formatting rule
// for top N (default is top 10) by given priority, criteria type and format
3226
// settings.
3227
func drawCondFmtTop10(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
3228
	c := &xlsxCfRule{
xurime's avatar
xurime 已提交
3229 3230 3231 3232 3233
		Priority:   p + 1,
		StopIfTrue: format.StopIfTrue,
		Bottom:     format.Type == "bottom",
		Type:       validType[format.Type],
		Rank:       10,
3234
		DxfID:      intPtr(format.Format),
xurime's avatar
xurime 已提交
3235
		Percent:    format.Percent,
3236
	}
3237
	if rank, err := strconv.Atoi(format.Value); err == nil {
3238 3239
		c.Rank = rank
	}
xurime's avatar
xurime 已提交
3240
	return c, nil
3241 3242
}

xurime's avatar
xurime 已提交
3243 3244 3245
// drawCondFmtAboveAverage provides a function to create conditional
// formatting rule for above average and below average by given priority,
// criteria type and format settings.
3246
func drawCondFmtAboveAverage(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
3247 3248
	return &xlsxCfRule{
		Priority:     p + 1,
xurime's avatar
xurime 已提交
3249
		StopIfTrue:   format.StopIfTrue,
3250
		Type:         validType[format.Type],
3251 3252
		AboveAverage: boolPtr(format.AboveAverage),
		DxfID:        intPtr(format.Format),
xurime's avatar
xurime 已提交
3253
	}, nil
3254 3255
}

xurime's avatar
xurime 已提交
3256
// drawCondFmtDuplicateUniqueValues provides a function to create conditional
3257 3258
// formatting rule for duplicate and unique values by given priority, criteria
// type and format settings.
3259
func drawCondFmtDuplicateUniqueValues(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
3260
	return &xlsxCfRule{
xurime's avatar
xurime 已提交
3261 3262 3263
		Priority:   p + 1,
		StopIfTrue: format.StopIfTrue,
		Type:       validType[format.Type],
3264
		DxfID:      intPtr(format.Format),
xurime's avatar
xurime 已提交
3265
	}, nil
3266 3267
}

xurime's avatar
xurime 已提交
3268 3269 3270
// drawCondFmtColorScale provides a function to create conditional formatting
// rule for color scale (include 2 color scale and 3 color scale) by given
// priority, criteria type and format settings.
3271
func drawCondFmtColorScale(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
	minValue := format.MinValue
	if minValue == "" {
		minValue = "0"
	}
	maxValue := format.MaxValue
	if maxValue == "" {
		maxValue = "0"
	}
	midValue := format.MidValue
	if midValue == "" {
		midValue = "50"
	}

3285
	c := &xlsxCfRule{
xurime's avatar
xurime 已提交
3286 3287 3288
		Priority:   p + 1,
		StopIfTrue: format.StopIfTrue,
		Type:       "colorScale",
3289 3290
		ColorScale: &xlsxColorScale{
			Cfvo: []*xlsxCfvo{
3291
				{Type: format.MinType, Val: minValue},
3292 3293 3294 3295 3296 3297 3298
			},
			Color: []*xlsxColor{
				{RGB: getPaletteColor(format.MinColor)},
			},
		},
	}
	if validType[format.Type] == "3_color_scale" {
3299
		c.ColorScale.Cfvo = append(c.ColorScale.Cfvo, &xlsxCfvo{Type: format.MidType, Val: midValue})
3300 3301
		c.ColorScale.Color = append(c.ColorScale.Color, &xlsxColor{RGB: getPaletteColor(format.MidColor)})
	}
3302
	c.ColorScale.Cfvo = append(c.ColorScale.Cfvo, &xlsxCfvo{Type: format.MaxType, Val: maxValue})
3303
	c.ColorScale.Color = append(c.ColorScale.Color, &xlsxColor{RGB: getPaletteColor(format.MaxColor)})
xurime's avatar
xurime 已提交
3304
	return c, nil
3305 3306
}

xurime's avatar
xurime 已提交
3307 3308
// drawCondFmtDataBar provides a function to create conditional formatting
// rule for data bar by given priority, criteria type and format settings.
3309
func drawCondFmtDataBar(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
xurime's avatar
xurime 已提交
3310 3311
	var x14CfRule *xlsxX14CfRule
	var extLst *xlsxExtLst
3312
	if format.BarSolid || format.BarDirection == "leftToRight" || format.BarDirection == "rightToLeft" || format.BarBorderColor != "" {
xurime's avatar
xurime 已提交
3313 3314 3315 3316 3317 3318
		extLst = &xlsxExtLst{Ext: fmt.Sprintf(`<ext uri="%s" xmlns:x14="%s"><x14:id>%s</x14:id></ext>`, ExtURIConditionalFormattingRuleID, NameSpaceSpreadSheetX14.Value, GUID)}
		x14CfRule = &xlsxX14CfRule{
			Type: validType[format.Type],
			ID:   GUID,
			DataBar: &xlsx14DataBar{
				MaxLength:         100,
3319 3320 3321
				Border:            format.BarBorderColor != "",
				Gradient:          !format.BarSolid,
				Direction:         format.BarDirection,
xurime's avatar
xurime 已提交
3322 3323 3324 3325 3326
				Cfvo:              []*xlsxCfvo{{Type: "autoMin"}, {Type: "autoMax"}},
				NegativeFillColor: &xlsxColor{RGB: "FFFF0000"},
				AxisColor:         &xlsxColor{RGB: "FFFF0000"},
			},
		}
3327
		if x14CfRule.DataBar.Border {
xurime's avatar
xurime 已提交
3328 3329 3330
			x14CfRule.DataBar.BorderColor = &xlsxColor{RGB: getPaletteColor(format.BarBorderColor)}
		}
	}
3331
	return &xlsxCfRule{
xurime's avatar
xurime 已提交
3332 3333 3334
		Priority:   p + 1,
		StopIfTrue: format.StopIfTrue,
		Type:       validType[format.Type],
3335
		DataBar: &xlsxDataBar{
xurime's avatar
xurime 已提交
3336
			ShowValue: boolPtr(!format.BarOnly),
3337
			Cfvo:      []*xlsxCfvo{{Type: format.MinType, Val: format.MinValue}, {Type: format.MaxType, Val: format.MaxValue}},
xurime's avatar
xurime 已提交
3338
			Color:     []*xlsxColor{{RGB: getPaletteColor(format.BarColor)}},
3339
		},
xurime's avatar
xurime 已提交
3340 3341
		ExtLst: extLst,
	}, x14CfRule
3342 3343
}

3344
// drawCondFmtExp provides a function to create conditional formatting rule
xurime's avatar
xurime 已提交
3345
// for expression by given priority, criteria type and format settings.
3346
func drawCondFmtExp(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
3347
	return &xlsxCfRule{
xurime's avatar
xurime 已提交
3348 3349 3350 3351
		Priority:   p + 1,
		StopIfTrue: format.StopIfTrue,
		Type:       validType[format.Type],
		Formula:    []string{format.Criteria},
3352
		DxfID:      intPtr(format.Format),
xurime's avatar
xurime 已提交
3353
	}, nil
3354 3355
}

3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367
// drawCondFmtErrors provides a function to create conditional formatting rule
// for cells with errors by given priority, criteria type and format settings.
func drawCondFmtErrors(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
	return &xlsxCfRule{
		Priority:   p + 1,
		StopIfTrue: format.StopIfTrue,
		Type:       validType[format.Type],
		Formula:    []string{fmt.Sprintf("ISERROR(%s)", ref)},
		DxfID:      intPtr(format.Format),
	}, nil
}

3368
// drawCondFmtNoErrors provides a function to create conditional formatting rule
3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379
// for cells without errors by given priority, criteria type and format settings.
func drawCondFmtNoErrors(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
	return &xlsxCfRule{
		Priority:   p + 1,
		StopIfTrue: format.StopIfTrue,
		Type:       validType[format.Type],
		Formula:    []string{fmt.Sprintf("NOT(ISERROR(%s))", ref)},
		DxfID:      intPtr(format.Format),
	}, nil
}

3380
// drawCondFmtBlanks provides a function to create conditional formatting rule
3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391
// for blank cells by given priority, criteria type and format settings.
func drawCondFmtBlanks(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
	return &xlsxCfRule{
		Priority:   p + 1,
		StopIfTrue: format.StopIfTrue,
		Type:       validType[format.Type],
		Formula:    []string{fmt.Sprintf("LEN(TRIM(%s))=0", ref)},
		DxfID:      intPtr(format.Format),
	}, nil
}

3392
// drawCondFmtNoBlanks provides a function to create conditional formatting rule
3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403
// for no blanks cells by given priority, criteria type and format settings.
func drawCondFmtNoBlanks(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
	return &xlsxCfRule{
		Priority:   p + 1,
		StopIfTrue: format.StopIfTrue,
		Type:       validType[format.Type],
		Formula:    []string{fmt.Sprintf("LEN(TRIM(%s))>0", ref)},
		DxfID:      intPtr(format.Format),
	}, nil
}

3404 3405
// drawCondFmtIconSet provides a function to create conditional formatting rule
// for icon set by given priority, criteria type and format settings.
3406
func drawCondFmtIconSet(p int, ct, ref, GUID string, format *ConditionalFormatOptions) (*xlsxCfRule, *xlsxX14CfRule) {
3407
	cfRule, ok := condFmtIconSetPresets[format.IconStyle]
3408 3409 3410 3411 3412 3413 3414
	if !ok {
		return nil, nil
	}
	cfRule.Priority = p + 1
	cfRule.IconSet.IconSet = format.IconStyle
	cfRule.IconSet.Reverse = format.ReverseIcons
	cfRule.IconSet.ShowValue = boolPtr(!format.IconsOnly)
3415
	cfRule.Type = validType[format.Type]
3416 3417 3418
	return cfRule, nil
}

xurime's avatar
xurime 已提交
3419 3420
// getPaletteColor provides a function to convert the RBG color by given
// string.
3421
func getPaletteColor(color string) string {
3422
	return "FF" + strings.ReplaceAll(strings.ToUpper(color), "#", "")
3423
}
xurime's avatar
xurime 已提交
3424

xurime's avatar
xurime 已提交
3425
// themeReader provides a function to get the pointer to the xl/theme/theme1.xml
xurime's avatar
xurime 已提交
3426
// structure after deserialization.
3427
func (f *File) themeReader() (*decodeTheme, error) {
3428
	if _, ok := f.Pkg.Load(defaultXMLPathTheme); !ok {
3429
		return nil, nil
3430
	}
3431
	theme := decodeTheme{}
3432
	if err := f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(defaultXMLPathTheme)))).
3433
		Decode(&theme); err != nil && err != io.EOF {
3434
		return &theme, err
3435
	}
3436
	return &theme, nil
xurime's avatar
xurime 已提交
3437 3438 3439 3440 3441 3442 3443
}

// ThemeColor applied the color with tint value.
func ThemeColor(baseColor string, tint float64) string {
	if tint == 0 {
		return "FF" + baseColor
	}
xurime's avatar
xurime 已提交
3444
	r, _ := strconv.ParseUint(baseColor[:2], 16, 64)
xurime's avatar
xurime 已提交
3445 3446
	g, _ := strconv.ParseUint(baseColor[2:4], 16, 64)
	b, _ := strconv.ParseUint(baseColor[4:6], 16, 64)
3447
	var h, s, l float64
xurime's avatar
xurime 已提交
3448
	if r <= math.MaxUint8 && g <= math.MaxUint8 && b <= math.MaxUint8 {
3449 3450
		h, s, l = RGBToHSL(uint8(r), uint8(g), uint8(b))
	}
xurime's avatar
xurime 已提交
3451
	if tint < 0 {
3452
		l *= 1 + tint
xurime's avatar
xurime 已提交
3453 3454 3455 3456 3457 3458
	} else {
		l = l*(1-tint) + (1 - (1 - tint))
	}
	br, bg, bb := HSLToRGB(h, s, l)
	return fmt.Sprintf("FF%02X%02X%02X", br, bg, bb)
}