styles.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. package excelize
  2. import (
  3. "encoding/json"
  4. "encoding/xml"
  5. "fmt"
  6. "math"
  7. "strconv"
  8. "strings"
  9. )
  10. // Excel styles can reference number formats that are built-in, all of which
  11. // have an id less than 164. This is a possibly incomplete list comprised of as
  12. // many of them as I could find.
  13. var builtInNumFmt = map[int]string{
  14. 0: "general",
  15. 1: "0",
  16. 2: "0.00",
  17. 3: "#,##0",
  18. 4: "#,##0.00",
  19. 9: "0%",
  20. 10: "0.00%",
  21. 11: "0.00e+00",
  22. 12: "# ?/?",
  23. 13: "# ??/??",
  24. 14: "mm-dd-yy",
  25. 15: "d-mmm-yy",
  26. 16: "d-mmm",
  27. 17: "mmm-yy",
  28. 18: "h:mm am/pm",
  29. 19: "h:mm:ss am/pm",
  30. 20: "h:mm",
  31. 21: "h:mm:ss",
  32. 22: "m/d/yy h:mm",
  33. 37: "#,##0 ;(#,##0)",
  34. 38: "#,##0 ;[red](#,##0)",
  35. 39: "#,##0.00;(#,##0.00)",
  36. 40: "#,##0.00;[red](#,##0.00)",
  37. 41: `_(* #,##0_);_(* \(#,##0\);_(* "-"_);_(@_)`,
  38. 42: `_("$"* #,##0_);_("$* \(#,##0\);_("$"* "-"_);_(@_)`,
  39. 43: `_(* #,##0.00_);_(* \(#,##0.00\);_(* "-"??_);_(@_)`,
  40. 44: `_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)`,
  41. 45: "mm:ss",
  42. 46: "[h]:mm:ss",
  43. 47: "mmss.0",
  44. 48: "##0.0e+0",
  45. 49: "@",
  46. }
  47. // builtInNumFmtFunc defined the format conversion functions map. Partial format
  48. // code doesn't support currently and will return original string.
  49. var builtInNumFmtFunc = map[int]func(i int, v string) string{
  50. 0: formatToString,
  51. 1: formatToInt,
  52. 2: formatToFloat,
  53. 3: formatToInt,
  54. 4: formatToFloat,
  55. 9: formatToC,
  56. 10: formatToD,
  57. 11: formatToE,
  58. 12: formatToString, // Doesn't support currently
  59. 13: formatToString, // Doesn't support currently
  60. 14: parseTime,
  61. 15: parseTime,
  62. 16: parseTime,
  63. 17: parseTime,
  64. 18: parseTime,
  65. 19: parseTime,
  66. 20: parseTime,
  67. 21: parseTime,
  68. 22: parseTime,
  69. 37: formatToA,
  70. 38: formatToA,
  71. 39: formatToB,
  72. 40: formatToB,
  73. 41: formatToString, // Doesn't support currently
  74. 42: formatToString, // Doesn't support currently
  75. 43: formatToString, // Doesn't support currently
  76. 44: formatToString, // Doesn't support currently
  77. 45: parseTime,
  78. 46: parseTime,
  79. 47: parseTime,
  80. 48: formatToE,
  81. 49: formatToString,
  82. }
  83. // formatToString provides function to return original string by given built-in
  84. // number formats code and cell string.
  85. func formatToString(i int, v string) string {
  86. return v
  87. }
  88. // formatToInt provides function to convert original string to integer format as
  89. // string type by given built-in number formats code and cell string.
  90. func formatToInt(i int, v string) string {
  91. f, err := strconv.ParseFloat(v, 64)
  92. if err != nil {
  93. return v
  94. }
  95. return fmt.Sprintf("%d", int(f))
  96. }
  97. // formatToFloat provides function to convert original string to float format as
  98. // string type by given built-in number formats code and cell string.
  99. func formatToFloat(i int, v string) string {
  100. f, err := strconv.ParseFloat(v, 64)
  101. if err != nil {
  102. return v
  103. }
  104. return fmt.Sprintf("%.2f", f)
  105. }
  106. // formatToA provides function to convert original string to special format as
  107. // string type by given built-in number formats code and cell string.
  108. func formatToA(i int, v string) string {
  109. f, err := strconv.ParseFloat(v, 64)
  110. if err != nil {
  111. return v
  112. }
  113. if f < 0 {
  114. t := int(math.Abs(f))
  115. return fmt.Sprintf("(%d)", t)
  116. }
  117. t := int(f)
  118. return fmt.Sprintf("%d", t)
  119. }
  120. // formatToB provides function to convert original string to special format as
  121. // string type by given built-in number formats code and cell string.
  122. func formatToB(i int, v string) string {
  123. f, err := strconv.ParseFloat(v, 64)
  124. if err != nil {
  125. return v
  126. }
  127. if f < 0 {
  128. return fmt.Sprintf("(%.2f)", f)
  129. }
  130. return fmt.Sprintf("%.2f", f)
  131. }
  132. // formatToC provides function to convert original string to special format as
  133. // string type by given built-in number formats code and cell string.
  134. func formatToC(i int, v string) string {
  135. f, err := strconv.ParseFloat(v, 64)
  136. if err != nil {
  137. return v
  138. }
  139. f = f * 100
  140. return fmt.Sprintf("%d%%", int(f))
  141. }
  142. // formatToD provides function to convert original string to special format as
  143. // string type by given built-in number formats code and cell string.
  144. func formatToD(i int, v string) string {
  145. f, err := strconv.ParseFloat(v, 64)
  146. if err != nil {
  147. return v
  148. }
  149. f = f * 100
  150. return fmt.Sprintf("%.2f%%", f)
  151. }
  152. // formatToE provides function to convert original string to special format as
  153. // string type by given built-in number formats code and cell string.
  154. func formatToE(i int, v string) string {
  155. f, err := strconv.ParseFloat(v, 64)
  156. if err != nil {
  157. return v
  158. }
  159. return fmt.Sprintf("%.e", f)
  160. }
  161. // parseTime provides function to returns a string parsed using time.Time.
  162. // Replace Excel placeholders with Go time placeholders. For example, replace
  163. // yyyy with 2006. These are in a specific order, due to the fact that m is used
  164. // in month, minute, and am/pm. It would be easier to fix that with regular
  165. // expressions, but if it's possible to keep this simple it would be easier to
  166. // maintain. Full-length month and days (e.g. March, Tuesday) have letters in
  167. // them that would be replaced by other characters below (such as the 'h' in
  168. // March, or the 'd' in Tuesday) below. First we convert them to arbitrary
  169. // characters unused in Excel Date formats, and then at the end, turn them to
  170. // what they should actually be.
  171. func parseTime(i int, v string) string {
  172. f, err := strconv.ParseFloat(v, 64)
  173. if err != nil {
  174. return v
  175. }
  176. val := timeFromExcelTime(f, false)
  177. format := builtInNumFmt[i]
  178. replacements := []struct{ xltime, gotime string }{
  179. {"yyyy", "2006"},
  180. {"yy", "06"},
  181. {"mmmm", "%%%%"},
  182. {"dddd", "&&&&"},
  183. {"dd", "02"},
  184. {"d", "2"},
  185. {"mmm", "Jan"},
  186. {"mmss", "0405"},
  187. {"ss", "05"},
  188. {"hh", "15"},
  189. {"h", "3"},
  190. {"mm:", "04:"},
  191. {":mm", ":04"},
  192. {"mm", "01"},
  193. {"am/pm", "pm"},
  194. {"m/", "1/"},
  195. {"%%%%", "January"},
  196. {"&&&&", "Monday"},
  197. }
  198. for _, repl := range replacements {
  199. format = strings.Replace(format, repl.xltime, repl.gotime, 1)
  200. }
  201. // If the hour is optional, strip it out, along with the possible dangling
  202. // colon that would remain.
  203. if val.Hour() < 1 {
  204. format = strings.Replace(format, "]:", "]", 1)
  205. format = strings.Replace(format, "[3]", "", 1)
  206. format = strings.Replace(format, "[15]", "", 1)
  207. } else {
  208. format = strings.Replace(format, "[3]", "3", 1)
  209. format = strings.Replace(format, "[15]", "15", 1)
  210. }
  211. return val.Format(format)
  212. }
  213. // stylesReader provides function to get the pointer to the structure after
  214. // deserialization of xl/styles.xml.
  215. func (f *File) stylesReader() *xlsxStyleSheet {
  216. if f.Styles == nil {
  217. var styleSheet xlsxStyleSheet
  218. xml.Unmarshal([]byte(f.readXML("xl/styles.xml")), &styleSheet)
  219. f.Styles = &styleSheet
  220. }
  221. return f.Styles
  222. }
  223. // styleSheetWriter provides function to save xl/styles.xml after serialize
  224. // structure.
  225. func (f *File) styleSheetWriter() {
  226. if f.Styles != nil {
  227. output, _ := xml.Marshal(f.Styles)
  228. f.saveFileList("xl/styles.xml", replaceWorkSheetsRelationshipsNameSpace(string(output)))
  229. }
  230. }
  231. // parseFormatStyleSet provides function to parse the format settings of the
  232. // borders.
  233. func parseFormatStyleSet(style string) (*formatCellStyle, error) {
  234. var format formatCellStyle
  235. err := json.Unmarshal([]byte(style), &format)
  236. return &format, err
  237. }
  238. // NewStyle provides function to create style for cells by given style format.
  239. // Note that the color field uses RGB color code.
  240. //
  241. // The following shows the border styles sorted by excelize index number:
  242. //
  243. // +-------+---------------+--------+-----------------+
  244. // | Index | Name | Weight | Style |
  245. // +=======+===============+========+=================+
  246. // | 0 | None | 0 | |
  247. // +-------+---------------+--------+-----------------+
  248. // | 1 | Continuous | 1 | ``-----------`` |
  249. // +-------+---------------+--------+-----------------+
  250. // | 2 | Continuous | 2 | ``-----------`` |
  251. // +-------+---------------+--------+-----------------+
  252. // | 3 | Dash | 1 | ``- - - - - -`` |
  253. // +-------+---------------+--------+-----------------+
  254. // | 4 | Dot | 1 | ``. . . . . .`` |
  255. // +-------+---------------+--------+-----------------+
  256. // | 5 | Continuous | 3 | ``-----------`` |
  257. // +-------+---------------+--------+-----------------+
  258. // | 6 | Double | 3 | ``===========`` |
  259. // +-------+---------------+--------+-----------------+
  260. // | 7 | Continuous | 0 | ``-----------`` |
  261. // +-------+---------------+--------+-----------------+
  262. // | 8 | Dash | 2 | ``- - - - - -`` |
  263. // +-------+---------------+--------+-----------------+
  264. // | 9 | Dash Dot | 1 | ``- . - . - .`` |
  265. // +-------+---------------+--------+-----------------+
  266. // | 10 | Dash Dot | 2 | ``- . - . - .`` |
  267. // +-------+---------------+--------+-----------------+
  268. // | 11 | Dash Dot Dot | 1 | ``- . . - . .`` |
  269. // +-------+---------------+--------+-----------------+
  270. // | 12 | Dash Dot Dot | 2 | ``- . . - . .`` |
  271. // +-------+---------------+--------+-----------------+
  272. // | 13 | SlantDash Dot | 2 | ``/ - . / - .`` |
  273. // +-------+---------------+--------+-----------------+
  274. //
  275. // The following shows the borders in the order shown in the Excel dialog:
  276. //
  277. // +-------+-----------------+-------+-----------------+
  278. // | Index | Style | Index | Style |
  279. // +=======+=================+=======+=================+
  280. // | 0 | None | 12 | ``- . . - . .`` |
  281. // +-------+-----------------+-------+-----------------+
  282. // | 7 | ``-----------`` | 13 | ``/ - . / - .`` |
  283. // +-------+-----------------+-------+-----------------+
  284. // | 4 | ``. . . . . .`` | 10 | ``- . - . - .`` |
  285. // +-------+-----------------+-------+-----------------+
  286. // | 11 | ``- . . - . .`` | 8 | ``- - - - - -`` |
  287. // +-------+-----------------+-------+-----------------+
  288. // | 9 | ``- . - . - .`` | 2 | ``-----------`` |
  289. // +-------+-----------------+-------+-----------------+
  290. // | 3 | ``- - - - - -`` | 5 | ``-----------`` |
  291. // +-------+-----------------+-------+-----------------+
  292. // | 1 | ``-----------`` | 6 | ``===========`` |
  293. // +-------+-----------------+-------+-----------------+
  294. //
  295. // The following shows the shading styles sorted by excelize index number:
  296. //
  297. // +-------+-----------------+-------+-----------------+
  298. // | Index | Style | Index | Style |
  299. // +=======+=================+=======+=================+
  300. // | 0 | Horizontal | 3 | Diagonal down |
  301. // +-------+-----------------+-------+-----------------+
  302. // | 1 | Vertical | 4 | From corner |
  303. // +-------+-----------------+-------+-----------------+
  304. // | 2 | Diagonal Up | 5 | From center |
  305. // +-------+-----------------+-------+-----------------+
  306. //
  307. // The following shows the patterns styles sorted by excelize index number:
  308. //
  309. // +-------+-----------------+-------+-----------------+
  310. // | Index | Style | Index | Style |
  311. // +=======+=================+=======+=================+
  312. // | 0 | None | 10 | darkTrellis |
  313. // +-------+-----------------+-------+-----------------+
  314. // | 1 | solid | 11 | lightHorizontal |
  315. // +-------+-----------------+-------+-----------------+
  316. // | 2 | mediumGray | 12 | lightVertical |
  317. // +-------+-----------------+-------+-----------------+
  318. // | 3 | darkGray | 13 | lightDown |
  319. // +-------+-----------------+-------+-----------------+
  320. // | 4 | lightGray | 14 | lightUp |
  321. // +-------+-----------------+-------+-----------------+
  322. // | 5 | darkHorizontal | 15 | lightGrid |
  323. // +-------+-----------------+-------+-----------------+
  324. // | 6 | darkVertical | 16 | lightTrellis |
  325. // +-------+-----------------+-------+-----------------+
  326. // | 7 | darkDown | 17 | gray125 |
  327. // +-------+-----------------+-------+-----------------+
  328. // | 8 | darkUp | 18 | gray0625 |
  329. // +-------+-----------------+-------+-----------------+
  330. // | 9 | darkGrid | | |
  331. // +-------+-----------------+-------+-----------------+
  332. //
  333. // The following the type of horizontal alignment in cells:
  334. //
  335. // +------------------+
  336. // | Style |
  337. // +==================+
  338. // | left |
  339. // +------------------+
  340. // | center |
  341. // +------------------+
  342. // | right |
  343. // +------------------+
  344. // | fill |
  345. // +------------------+
  346. // | justify |
  347. // +------------------+
  348. // | centerContinuous |
  349. // +------------------+
  350. // | distributed |
  351. // +------------------+
  352. //
  353. // The following the type of vertical alignment in cells:
  354. //
  355. // +------------------+
  356. // | Style |
  357. // +==================+
  358. // | top |
  359. // +------------------+
  360. // | center |
  361. // +------------------+
  362. // | justify |
  363. // +------------------+
  364. // | distributed |
  365. // +------------------+
  366. //
  367. // The following the type of font underline style:
  368. //
  369. // +------------------+
  370. // | Style |
  371. // +==================+
  372. // | single |
  373. // +------------------+
  374. // | double |
  375. // +------------------+
  376. //
  377. // Excel's built-in formats are shown in the following table:
  378. //
  379. // +-------+----------------------------------------------------+
  380. // | Index | Format String |
  381. // +=======+====================================================+
  382. // | 0 | General |
  383. // +-------+----------------------------------------------------+
  384. // | 1 | 0 |
  385. // +-------+----------------------------------------------------+
  386. // | 2 | 0.00 |
  387. // +-------+----------------------------------------------------+
  388. // | 3 | #,##0 |
  389. // +-------+----------------------------------------------------+
  390. // | 4 | #,##0.00 |
  391. // +-------+----------------------------------------------------+
  392. // | 5 | ($#,##0_);($#,##0) |
  393. // +-------+----------------------------------------------------+
  394. // | 6 | ($#,##0_);[Red]($#,##0) |
  395. // +-------+----------------------------------------------------+
  396. // | 7 | ($#,##0.00_);($#,##0.00) |
  397. // +-------+----------------------------------------------------+
  398. // | 8 | ($#,##0.00_);[Red]($#,##0.00) |
  399. // +-------+----------------------------------------------------+
  400. // | 9 | 0% |
  401. // +-------+----------------------------------------------------+
  402. // | 10 | 0.00% |
  403. // +-------+----------------------------------------------------+
  404. // | 11 | 0.00E+00 |
  405. // +-------+----------------------------------------------------+
  406. // | 12 | # ?/? |
  407. // +-------+----------------------------------------------------+
  408. // | 13 | # ??/?? |
  409. // +-------+----------------------------------------------------+
  410. // | 14 | m/d/yy |
  411. // +-------+----------------------------------------------------+
  412. // | 15 | d-mmm-yy |
  413. // +-------+----------------------------------------------------+
  414. // | 16 | d-mmm |
  415. // +-------+----------------------------------------------------+
  416. // | 17 | mmm-yy |
  417. // +-------+----------------------------------------------------+
  418. // | 18 | h:mm AM/PM |
  419. // +-------+----------------------------------------------------+
  420. // | 19 | h:mm:ss AM/PM |
  421. // +-------+----------------------------------------------------+
  422. // | 20 | h:mm |
  423. // +-------+----------------------------------------------------+
  424. // | 21 | h:mm:ss |
  425. // +-------+----------------------------------------------------+
  426. // | 22 | m/d/yy h:mm |
  427. // +-------+----------------------------------------------------+
  428. // | ... | ... |
  429. // +-------+----------------------------------------------------+
  430. // | 37 | (#,##0_);(#,##0) |
  431. // +-------+----------------------------------------------------+
  432. // | 38 | (#,##0_);[Red](#,##0) |
  433. // +-------+----------------------------------------------------+
  434. // | 39 | (#,##0.00_);(#,##0.00) |
  435. // +-------+----------------------------------------------------+
  436. // | 40 | (#,##0.00_);[Red](#,##0.00) |
  437. // +-------+----------------------------------------------------+
  438. // | 41 | _(* #,##0_);_(* (#,##0);_(* "-"_);_(@_) |
  439. // +-------+----------------------------------------------------+
  440. // | 42 | _($* #,##0_);_($* (#,##0);_($* "-"_);_(@_) |
  441. // +-------+----------------------------------------------------+
  442. // | 43 | _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_) |
  443. // +-------+----------------------------------------------------+
  444. // | 44 | _($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_) |
  445. // +-------+----------------------------------------------------+
  446. // | 45 | mm:ss |
  447. // +-------+----------------------------------------------------+
  448. // | 46 | [h]:mm:ss |
  449. // +-------+----------------------------------------------------+
  450. // | 47 | mm:ss.0 |
  451. // +-------+----------------------------------------------------+
  452. // | 48 | ##0.0E+0 |
  453. // +-------+----------------------------------------------------+
  454. // | 49 | @ |
  455. // +-------+----------------------------------------------------+
  456. //
  457. func (f *File) NewStyle(style string) (int, error) {
  458. var cellXfsID int
  459. styleSheet := f.stylesReader()
  460. formatCellStyle, err := parseFormatStyleSet(style)
  461. if err != nil {
  462. return cellXfsID, err
  463. }
  464. numFmtID := setNumFmt(styleSheet, formatCellStyle)
  465. fontID := setFont(styleSheet, formatCellStyle)
  466. borderID := setBorders(styleSheet, formatCellStyle)
  467. fillID := setFills(styleSheet, formatCellStyle)
  468. applyAlignment, alignment := setAlignment(styleSheet, formatCellStyle)
  469. cellXfsID = setCellXfs(styleSheet, fontID, numFmtID, fillID, borderID, applyAlignment, alignment)
  470. return cellXfsID, nil
  471. }
  472. // setFont provides function to add font style by given cell format settings.
  473. func setFont(style *xlsxStyleSheet, formatCellStyle *formatCellStyle) int {
  474. if formatCellStyle.Font == nil {
  475. return 0
  476. }
  477. fontUnderlineType := map[string]string{"single": "single", "double": "double"}
  478. if formatCellStyle.Font.Family == "" {
  479. formatCellStyle.Font.Family = "Calibri"
  480. }
  481. if formatCellStyle.Font.Size < 1 {
  482. formatCellStyle.Font.Size = 11
  483. }
  484. if formatCellStyle.Font.Color == "" {
  485. formatCellStyle.Font.Color = "#000000"
  486. }
  487. f := font{
  488. B: formatCellStyle.Font.Bold,
  489. I: formatCellStyle.Font.Italic,
  490. Sz: &attrValInt{Val: formatCellStyle.Font.Size},
  491. Color: &xlsxColor{RGB: getPaletteColor(formatCellStyle.Font.Color)},
  492. Name: &attrValString{Val: formatCellStyle.Font.Family},
  493. Family: &attrValInt{Val: 2},
  494. Scheme: &attrValString{Val: "minor"},
  495. }
  496. val, ok := fontUnderlineType[formatCellStyle.Font.Underline]
  497. if ok {
  498. f.U = &attrValString{Val: val}
  499. }
  500. font, _ := xml.Marshal(f)
  501. style.Fonts.Count++
  502. style.Fonts.Font = append(style.Fonts.Font, &xlsxFont{
  503. Font: string(font[6 : len(font)-7]),
  504. })
  505. return style.Fonts.Count - 1
  506. }
  507. // setNumFmt provides function to check if number format code in the range of
  508. // built-in values.
  509. func setNumFmt(style *xlsxStyleSheet, formatCellStyle *formatCellStyle) int {
  510. _, ok := builtInNumFmt[formatCellStyle.NumFmt]
  511. if !ok {
  512. return 0
  513. }
  514. return formatCellStyle.NumFmt
  515. }
  516. // setFills provides function to add fill elements in the styles.xml by given
  517. // cell format settings.
  518. func setFills(style *xlsxStyleSheet, formatCellStyle *formatCellStyle) int {
  519. var patterns = []string{
  520. "none",
  521. "solid",
  522. "mediumGray",
  523. "darkGray",
  524. "lightGray",
  525. "darkHorizontal",
  526. "darkVertical",
  527. "darkDown",
  528. "darkUp",
  529. "darkGrid",
  530. "darkTrellis",
  531. "lightHorizontal",
  532. "lightVertical",
  533. "lightDown",
  534. "lightUp",
  535. "lightGrid",
  536. "lightTrellis",
  537. "gray125",
  538. "gray0625",
  539. }
  540. var variants = []float64{
  541. 90,
  542. 0,
  543. 45,
  544. 135,
  545. }
  546. var fill xlsxFill
  547. switch formatCellStyle.Fill.Type {
  548. case "gradient":
  549. if len(formatCellStyle.Fill.Color) != 2 {
  550. break
  551. }
  552. var gradient xlsxGradientFill
  553. switch formatCellStyle.Fill.Shading {
  554. case 0, 1, 2, 3:
  555. gradient.Degree = variants[formatCellStyle.Fill.Shading]
  556. case 4:
  557. gradient.Type = "path"
  558. case 5:
  559. gradient.Type = "path"
  560. gradient.Bottom = 0.5
  561. gradient.Left = 0.5
  562. gradient.Right = 0.5
  563. gradient.Top = 0.5
  564. default:
  565. break
  566. }
  567. var stops []*xlsxGradientFillStop
  568. for index, color := range formatCellStyle.Fill.Color {
  569. var stop xlsxGradientFillStop
  570. stop.Position = float64(index)
  571. stop.Color.RGB = getPaletteColor(color)
  572. stops = append(stops, &stop)
  573. }
  574. gradient.Stop = stops
  575. fill.GradientFill = &gradient
  576. case "pattern":
  577. if formatCellStyle.Fill.Pattern > 18 || formatCellStyle.Fill.Pattern < 0 {
  578. break
  579. }
  580. if len(formatCellStyle.Fill.Color) < 1 {
  581. break
  582. }
  583. var pattern xlsxPatternFill
  584. pattern.PatternType = patterns[formatCellStyle.Fill.Pattern]
  585. pattern.FgColor.RGB = getPaletteColor(formatCellStyle.Fill.Color[0])
  586. fill.PatternFill = &pattern
  587. }
  588. style.Fills.Count++
  589. style.Fills.Fill = append(style.Fills.Fill, &fill)
  590. return style.Fills.Count - 1
  591. }
  592. // setAlignment provides function to formatting information pertaining to text
  593. // alignment in cells. There are a variety of choices for how text is aligned
  594. // both horizontally and vertically, as well as indentation settings, and so on.
  595. func setAlignment(style *xlsxStyleSheet, formatCellStyle *formatCellStyle) (bool, *xlsxAlignment) {
  596. if formatCellStyle.Alignment == nil {
  597. return false, &xlsxAlignment{}
  598. }
  599. var alignment = xlsxAlignment{
  600. Horizontal: formatCellStyle.Alignment.Horizontal,
  601. Indent: formatCellStyle.Alignment.Indent,
  602. JustifyLastLine: formatCellStyle.Alignment.JustifyLastLine,
  603. ReadingOrder: formatCellStyle.Alignment.ReadingOrder,
  604. RelativeIndent: formatCellStyle.Alignment.RelativeIndent,
  605. ShrinkToFit: formatCellStyle.Alignment.ShrinkToFit,
  606. TextRotation: formatCellStyle.Alignment.TextRotation,
  607. Vertical: formatCellStyle.Alignment.Vertical,
  608. WrapText: formatCellStyle.Alignment.WrapText,
  609. }
  610. return true, &alignment
  611. }
  612. // setBorders provides function to add border elements in the styles.xml by
  613. // given borders format settings.
  614. func setBorders(style *xlsxStyleSheet, formatCellStyle *formatCellStyle) int {
  615. var styles = []string{
  616. "none",
  617. "thin",
  618. "medium",
  619. "dashed",
  620. "dotted",
  621. "thick",
  622. "double",
  623. "hair",
  624. "mediumDashed",
  625. "dashDot",
  626. "mediumDashDot",
  627. "dashDotDot",
  628. "mediumDashDotDot",
  629. "slantDashDot",
  630. }
  631. var border xlsxBorder
  632. for _, v := range formatCellStyle.Border {
  633. if v.Style > 13 || v.Style < 0 {
  634. continue
  635. }
  636. var color xlsxColor
  637. color.RGB = getPaletteColor(v.Color)
  638. switch v.Type {
  639. case "left":
  640. border.Left.Style = styles[v.Style]
  641. border.Left.Color = &color
  642. case "right":
  643. border.Right.Style = styles[v.Style]
  644. border.Right.Color = &color
  645. case "top":
  646. border.Top.Style = styles[v.Style]
  647. border.Top.Color = &color
  648. case "bottom":
  649. border.Bottom.Style = styles[v.Style]
  650. border.Bottom.Color = &color
  651. case "diagonalUp":
  652. border.Diagonal.Style = styles[v.Style]
  653. border.Diagonal.Color = &color
  654. border.DiagonalUp = true
  655. case "diagonalDown":
  656. border.Diagonal.Style = styles[v.Style]
  657. border.Diagonal.Color = &color
  658. border.DiagonalDown = true
  659. }
  660. }
  661. style.Borders.Count++
  662. style.Borders.Border = append(style.Borders.Border, &border)
  663. return style.Borders.Count - 1
  664. }
  665. // setCellXfs provides function to set describes all of the formatting for a
  666. // cell.
  667. func setCellXfs(style *xlsxStyleSheet, fontID, numFmtID, fillID, borderID int, applyAlignment bool, alignment *xlsxAlignment) int {
  668. var xf xlsxXf
  669. xf.FontID = fontID
  670. if fontID != 0 {
  671. xf.ApplyFont = true
  672. }
  673. xf.NumFmtID = numFmtID
  674. if numFmtID != 0 {
  675. xf.ApplyNumberFormat = true
  676. }
  677. xf.FillID = fillID
  678. xf.BorderID = borderID
  679. style.CellXfs.Count++
  680. xf.Alignment = alignment
  681. xf.ApplyAlignment = applyAlignment
  682. style.CellXfs.Xf = append(style.CellXfs.Xf, xf)
  683. return style.CellXfs.Count - 1
  684. }
  685. // SetCellStyle provides function to add style attribute for cells by given
  686. // worksheet sheet index, coordinate area and style ID. Note that diagonalDown
  687. // and diagonalUp type border should be use same color in the same coordinate
  688. // area.
  689. //
  690. // For example create a borders of cell H9 on Sheet1:
  691. //
  692. // style, err := xlsx.NewStyle(`{"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}]}`)
  693. // if err != nil {
  694. // fmt.Println(err)
  695. // }
  696. // xlsx.SetCellStyle("Sheet1", "H9", "H9", style)
  697. //
  698. // Set gradient fill with vertical variants shading styles for cell H9 on
  699. // Sheet1:
  700. //
  701. // style, err := xlsx.NewStyle(`{"fill":{"type":"gradient","color":["#FFFFFF","#E0EBF5"],"shading":1}}`)
  702. // if err != nil {
  703. // fmt.Println(err)
  704. // }
  705. // xlsx.SetCellStyle("Sheet1", "H9", "H9", style)
  706. //
  707. // Set solid style pattern fill for cell H9 on Sheet1:
  708. //
  709. // style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["#E0EBF5"],"pattern":1}}`)
  710. // if err != nil {
  711. // fmt.Println(err)
  712. // }
  713. // xlsx.SetCellStyle("Sheet1", "H9", "H9", style)
  714. //
  715. // Set alignment style for cell H9 on Sheet1:
  716. //
  717. // style, err := xlsx.NewStyle(`{"alignment":{"horizontal":"center","ident":1,"justify_last_line":true,"reading_order":0,"relative_indent":1,"shrink_to_fit":true,"text_rotation":45,"vertical":"","wrap_text":true}}`)
  718. // if err != nil {
  719. // fmt.Println(err)
  720. // }
  721. // xlsx.SetCellStyle("Sheet1", "H9", "H9", style)
  722. //
  723. // Dates and times in Excel are represented by real numbers, for example "Apr 7
  724. // 2017 12:00 PM" is represented by the number 42920.5. Set date and time format
  725. // for cell H9 on Sheet1:
  726. //
  727. // xlsx.SetCellValue("Sheet1", "H9", 42920.5)
  728. // style, err := xlsx.NewStyle(`{"number_format": 22}`)
  729. // if err != nil {
  730. // fmt.Println(err)
  731. // }
  732. // xlsx.SetCellStyle("Sheet1", "H9", "H9", style)
  733. //
  734. // Set font style for cell H9 on Sheet1:
  735. //
  736. // style, err := xlsx.NewStyle(`{"font":{"bold":true,"italic":true,"family":"Berlin Sans FB Demi","size":36,"color":"#777777"}}`)
  737. // if err != nil {
  738. // fmt.Println(err)
  739. // }
  740. // xlsx.SetCellStyle("Sheet1", "H9", "H9", style)
  741. //
  742. func (f *File) SetCellStyle(sheet, hcell, vcell string, styleID int) {
  743. hcell = strings.ToUpper(hcell)
  744. vcell = strings.ToUpper(vcell)
  745. // Coordinate conversion, convert C1:B3 to 2,0,1,2.
  746. hcol := string(strings.Map(letterOnlyMapF, hcell))
  747. hrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, hcell))
  748. hyAxis := hrow - 1
  749. hxAxis := TitleToNumber(hcol)
  750. vcol := string(strings.Map(letterOnlyMapF, vcell))
  751. vrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, vcell))
  752. vyAxis := vrow - 1
  753. vxAxis := TitleToNumber(vcol)
  754. if vxAxis < hxAxis {
  755. hcell, vcell = vcell, hcell
  756. vxAxis, hxAxis = hxAxis, vxAxis
  757. }
  758. if vyAxis < hyAxis {
  759. hcell, vcell = vcell, hcell
  760. vyAxis, hyAxis = hyAxis, vyAxis
  761. }
  762. // Correct the coordinate area, such correct C1:B3 to B1:C3.
  763. hcell = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1)
  764. vcell = ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
  765. xlsx := f.workSheetReader(sheet)
  766. completeRow(xlsx, vyAxis+1, vxAxis+1)
  767. completeCol(xlsx, vyAxis+1, vxAxis+1)
  768. for r, row := range xlsx.SheetData.Row {
  769. for k, c := range row.C {
  770. if checkCellInArea(c.R, hcell+":"+vcell) {
  771. xlsx.SheetData.Row[r].C[k].S = styleID
  772. }
  773. }
  774. }
  775. }
  776. // getPaletteColor provides function to convert the RBG color by given string.
  777. func getPaletteColor(color string) string {
  778. return "FF" + strings.Replace(strings.ToUpper(color), "#", "", -1)
  779. }