styles.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  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. // SetCellStyle provides function to set style for cells by given sheet index
  239. // and coordinate area in XLSX file. Note that the color field uses RGB color
  240. // code and diagonalDown and diagonalUp type border should be use same color in
  241. // the same coordinate area.
  242. //
  243. // For example create a borders of cell H9 on Sheet1:
  244. //
  245. // err := xlsx.SetCellStyle("Sheet1", "H9", "H9", `{"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}]}`)
  246. // if err != nil {
  247. // fmt.Println(err)
  248. // }
  249. //
  250. // Set gradient fill with vertical variants shading styles for cell H9 on
  251. // Sheet1:
  252. //
  253. // err := xlsx.SetCellStyle("Sheet1", "H9", "H9", `{"fill":{"type":"gradient","color":["#FFFFFF","#E0EBF5"],"shading":1}}`)
  254. // if err != nil {
  255. // fmt.Println(err)
  256. // }
  257. //
  258. // Set solid style pattern fill for cell H9 on Sheet1:
  259. //
  260. // err := xlsx.SetCellStyle("Sheet1", "H9", "H9", `{"fill":{"type":"pattern","color":["#E0EBF5"],"pattern":1}}`)
  261. // if err != nil {
  262. // fmt.Println(err)
  263. // }
  264. //
  265. // Set alignment style for cell H9 on Sheet1:
  266. //
  267. // err = xlsx.SetCellStyle("Sheet1", "H9", "H9", `{"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}}`)
  268. // if err != nil {
  269. // fmt.Println(err)
  270. // }
  271. //
  272. // Dates and times in Excel are represented by real numbers, for example "Apr 7
  273. // 2017 12:00 PM" is represented by the number 42920.5. Set date and time format
  274. // for cell H9 on Sheet1:
  275. //
  276. // xlsx.SetCellValue("Sheet2", "H9", 42920.5)
  277. // err = xlsx.SetCellStyle("Sheet1", "H9", "H9", `{"number_format": 22}`)
  278. // if err != nil {
  279. // fmt.Println(err)
  280. // }
  281. //
  282. // Set font style for cell H9 on Sheet1:
  283. //
  284. // err = xlsx.SetCellStyle("Sheet1", "H9", "H9", `{"font":{"bold":true,"italic":true,"family":"Berlin Sans FB Demi","size":36,"color":"#777777"}}`)
  285. // if err != nil {
  286. // fmt.Println(err)
  287. // }
  288. //
  289. // The following shows the border styles sorted by excelize index number:
  290. //
  291. // +-------+---------------+--------+-----------------+
  292. // | Index | Name | Weight | Style |
  293. // +=======+===============+========+=================+
  294. // | 0 | None | 0 | |
  295. // +-------+---------------+--------+-----------------+
  296. // | 1 | Continuous | 1 | ``-----------`` |
  297. // +-------+---------------+--------+-----------------+
  298. // | 2 | Continuous | 2 | ``-----------`` |
  299. // +-------+---------------+--------+-----------------+
  300. // | 3 | Dash | 1 | ``- - - - - -`` |
  301. // +-------+---------------+--------+-----------------+
  302. // | 4 | Dot | 1 | ``. . . . . .`` |
  303. // +-------+---------------+--------+-----------------+
  304. // | 5 | Continuous | 3 | ``-----------`` |
  305. // +-------+---------------+--------+-----------------+
  306. // | 6 | Double | 3 | ``===========`` |
  307. // +-------+---------------+--------+-----------------+
  308. // | 7 | Continuous | 0 | ``-----------`` |
  309. // +-------+---------------+--------+-----------------+
  310. // | 8 | Dash | 2 | ``- - - - - -`` |
  311. // +-------+---------------+--------+-----------------+
  312. // | 9 | Dash Dot | 1 | ``- . - . - .`` |
  313. // +-------+---------------+--------+-----------------+
  314. // | 10 | Dash Dot | 2 | ``- . - . - .`` |
  315. // +-------+---------------+--------+-----------------+
  316. // | 11 | Dash Dot Dot | 1 | ``- . . - . .`` |
  317. // +-------+---------------+--------+-----------------+
  318. // | 12 | Dash Dot Dot | 2 | ``- . . - . .`` |
  319. // +-------+---------------+--------+-----------------+
  320. // | 13 | SlantDash Dot | 2 | ``/ - . / - .`` |
  321. // +-------+---------------+--------+-----------------+
  322. //
  323. // The following shows the borders in the order shown in the Excel dialog:
  324. //
  325. // +-------+-----------------+-------+-----------------+
  326. // | Index | Style | Index | Style |
  327. // +=======+=================+=======+=================+
  328. // | 0 | None | 12 | ``- . . - . .`` |
  329. // +-------+-----------------+-------+-----------------+
  330. // | 7 | ``-----------`` | 13 | ``/ - . / - .`` |
  331. // +-------+-----------------+-------+-----------------+
  332. // | 4 | ``. . . . . .`` | 10 | ``- . - . - .`` |
  333. // +-------+-----------------+-------+-----------------+
  334. // | 11 | ``- . . - . .`` | 8 | ``- - - - - -`` |
  335. // +-------+-----------------+-------+-----------------+
  336. // | 9 | ``- . - . - .`` | 2 | ``-----------`` |
  337. // +-------+-----------------+-------+-----------------+
  338. // | 3 | ``- - - - - -`` | 5 | ``-----------`` |
  339. // +-------+-----------------+-------+-----------------+
  340. // | 1 | ``-----------`` | 6 | ``===========`` |
  341. // +-------+-----------------+-------+-----------------+
  342. //
  343. // The following shows the shading styles sorted by excelize index number:
  344. //
  345. // +-------+-----------------+-------+-----------------+
  346. // | Index | Style | Index | Style |
  347. // +=======+=================+=======+=================+
  348. // | 0 | Horizontal | 3 | Diagonal down |
  349. // +-------+-----------------+-------+-----------------+
  350. // | 1 | Vertical | 4 | From corner |
  351. // +-------+-----------------+-------+-----------------+
  352. // | 2 | Diagonal Up | 5 | From center |
  353. // +-------+-----------------+-------+-----------------+
  354. //
  355. // The following shows the patterns styles sorted by excelize index number:
  356. //
  357. // +-------+-----------------+-------+-----------------+
  358. // | Index | Style | Index | Style |
  359. // +=======+=================+=======+=================+
  360. // | 0 | None | 10 | darkTrellis |
  361. // +-------+-----------------+-------+-----------------+
  362. // | 1 | solid | 11 | lightHorizontal |
  363. // +-------+-----------------+-------+-----------------+
  364. // | 2 | mediumGray | 12 | lightVertical |
  365. // +-------+-----------------+-------+-----------------+
  366. // | 3 | darkGray | 13 | lightDown |
  367. // +-------+-----------------+-------+-----------------+
  368. // | 4 | lightGray | 14 | lightUp |
  369. // +-------+-----------------+-------+-----------------+
  370. // | 5 | darkHorizontal | 15 | lightGrid |
  371. // +-------+-----------------+-------+-----------------+
  372. // | 6 | darkVertical | 16 | lightTrellis |
  373. // +-------+-----------------+-------+-----------------+
  374. // | 7 | darkDown | 17 | gray125 |
  375. // +-------+-----------------+-------+-----------------+
  376. // | 8 | darkUp | 18 | gray0625 |
  377. // +-------+-----------------+-------+-----------------+
  378. // | 9 | darkGrid | | |
  379. // +-------+-----------------+-------+-----------------+
  380. //
  381. // The following the type of horizontal alignment in cells:
  382. //
  383. // +------------------+
  384. // | Style |
  385. // +==================+
  386. // | left |
  387. // +------------------+
  388. // | center |
  389. // +------------------+
  390. // | right |
  391. // +------------------+
  392. // | fill |
  393. // +------------------+
  394. // | justify |
  395. // +------------------+
  396. // | centerContinuous |
  397. // +------------------+
  398. // | distributed |
  399. // +------------------+
  400. //
  401. // The following the type of vertical alignment in cells:
  402. //
  403. // +------------------+
  404. // | Style |
  405. // +==================+
  406. // | top |
  407. // +------------------+
  408. // | center |
  409. // +------------------+
  410. // | justify |
  411. // +------------------+
  412. // | distributed |
  413. // +------------------+
  414. //
  415. // The following the type of font underline style:
  416. //
  417. // +------------------+
  418. // | Style |
  419. // +==================+
  420. // | single |
  421. // +------------------+
  422. // | double |
  423. // +------------------+
  424. //
  425. // Excel's built-in formats are shown in the following table:
  426. //
  427. // +-------+----------------------------------------------------+
  428. // | Index | Format String |
  429. // +=======+====================================================+
  430. // | 0 | General |
  431. // +-------+----------------------------------------------------+
  432. // | 1 | 0 |
  433. // +-------+----------------------------------------------------+
  434. // | 2 | 0.00 |
  435. // +-------+----------------------------------------------------+
  436. // | 3 | #,##0 |
  437. // +-------+----------------------------------------------------+
  438. // | 4 | #,##0.00 |
  439. // +-------+----------------------------------------------------+
  440. // | 5 | ($#,##0_);($#,##0) |
  441. // +-------+----------------------------------------------------+
  442. // | 6 | ($#,##0_);[Red]($#,##0) |
  443. // +-------+----------------------------------------------------+
  444. // | 7 | ($#,##0.00_);($#,##0.00) |
  445. // +-------+----------------------------------------------------+
  446. // | 8 | ($#,##0.00_);[Red]($#,##0.00) |
  447. // +-------+----------------------------------------------------+
  448. // | 9 | 0% |
  449. // +-------+----------------------------------------------------+
  450. // | 10 | 0.00% |
  451. // +-------+----------------------------------------------------+
  452. // | 11 | 0.00E+00 |
  453. // +-------+----------------------------------------------------+
  454. // | 12 | # ?/? |
  455. // +-------+----------------------------------------------------+
  456. // | 13 | # ??/?? |
  457. // +-------+----------------------------------------------------+
  458. // | 14 | m/d/yy |
  459. // +-------+----------------------------------------------------+
  460. // | 15 | d-mmm-yy |
  461. // +-------+----------------------------------------------------+
  462. // | 16 | d-mmm |
  463. // +-------+----------------------------------------------------+
  464. // | 17 | mmm-yy |
  465. // +-------+----------------------------------------------------+
  466. // | 18 | h:mm AM/PM |
  467. // +-------+----------------------------------------------------+
  468. // | 19 | h:mm:ss AM/PM |
  469. // +-------+----------------------------------------------------+
  470. // | 20 | h:mm |
  471. // +-------+----------------------------------------------------+
  472. // | 21 | h:mm:ss |
  473. // +-------+----------------------------------------------------+
  474. // | 22 | m/d/yy h:mm |
  475. // +-------+----------------------------------------------------+
  476. // | ... | ... |
  477. // +-------+----------------------------------------------------+
  478. // | 37 | (#,##0_);(#,##0) |
  479. // +-------+----------------------------------------------------+
  480. // | 38 | (#,##0_);[Red](#,##0) |
  481. // +-------+----------------------------------------------------+
  482. // | 39 | (#,##0.00_);(#,##0.00) |
  483. // +-------+----------------------------------------------------+
  484. // | 40 | (#,##0.00_);[Red](#,##0.00) |
  485. // +-------+----------------------------------------------------+
  486. // | 41 | _(* #,##0_);_(* (#,##0);_(* "-"_);_(@_) |
  487. // +-------+----------------------------------------------------+
  488. // | 42 | _($* #,##0_);_($* (#,##0);_($* "-"_);_(@_) |
  489. // +-------+----------------------------------------------------+
  490. // | 43 | _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_) |
  491. // +-------+----------------------------------------------------+
  492. // | 44 | _($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_) |
  493. // +-------+----------------------------------------------------+
  494. // | 45 | mm:ss |
  495. // +-------+----------------------------------------------------+
  496. // | 46 | [h]:mm:ss |
  497. // +-------+----------------------------------------------------+
  498. // | 47 | mm:ss.0 |
  499. // +-------+----------------------------------------------------+
  500. // | 48 | ##0.0E+0 |
  501. // +-------+----------------------------------------------------+
  502. // | 49 | @ |
  503. // +-------+----------------------------------------------------+
  504. //
  505. func (f *File) SetCellStyle(sheet, hcell, vcell, style string) error {
  506. styleSheet := f.stylesReader()
  507. formatCellStyle, err := parseFormatStyleSet(style)
  508. if err != nil {
  509. return err
  510. }
  511. numFmtID := setNumFmt(styleSheet, formatCellStyle)
  512. fontID := setFont(styleSheet, formatCellStyle)
  513. borderID := setBorders(styleSheet, formatCellStyle)
  514. fillID := setFills(styleSheet, formatCellStyle)
  515. applyAlignment, alignment := setAlignment(styleSheet, formatCellStyle)
  516. cellXfsID := setCellXfs(styleSheet, fontID, numFmtID, fillID, borderID, applyAlignment, alignment)
  517. f.setCellStyle(sheet, hcell, vcell, cellXfsID)
  518. return err
  519. }
  520. // setFont provides function to add font style by given cell format settings.
  521. func setFont(style *xlsxStyleSheet, formatCellStyle *formatCellStyle) int {
  522. if formatCellStyle.Font == nil {
  523. return 0
  524. }
  525. fontUnderlineType := map[string]string{"single": "single", "double": "double"}
  526. if formatCellStyle.Font.Family == "" {
  527. formatCellStyle.Font.Family = "Calibri"
  528. }
  529. if formatCellStyle.Font.Size < 1 {
  530. formatCellStyle.Font.Size = 11
  531. }
  532. if formatCellStyle.Font.Color == "" {
  533. formatCellStyle.Font.Color = "#000000"
  534. }
  535. f := font{
  536. B: formatCellStyle.Font.Bold,
  537. I: formatCellStyle.Font.Italic,
  538. Sz: &attrValInt{Val: formatCellStyle.Font.Size},
  539. Color: &xlsxColor{RGB: getPaletteColor(formatCellStyle.Font.Color)},
  540. Name: &attrValString{Val: formatCellStyle.Font.Family},
  541. Family: &attrValInt{Val: 2},
  542. Scheme: &attrValString{Val: "minor"},
  543. }
  544. val, ok := fontUnderlineType[formatCellStyle.Font.Underline]
  545. if ok {
  546. f.U = &attrValString{Val: val}
  547. }
  548. font, _ := xml.Marshal(f)
  549. style.Fonts.Count++
  550. style.Fonts.Font = append(style.Fonts.Font, &xlsxFont{
  551. Font: string(font[6 : len(font)-7]),
  552. })
  553. return style.Fonts.Count - 1
  554. }
  555. // setNumFmt provides function to check if number format code in the range of
  556. // built-in values.
  557. func setNumFmt(style *xlsxStyleSheet, formatCellStyle *formatCellStyle) int {
  558. _, ok := builtInNumFmt[formatCellStyle.NumFmt]
  559. if !ok {
  560. return 0
  561. }
  562. return formatCellStyle.NumFmt
  563. }
  564. // setFills provides function to add fill elements in the styles.xml by given
  565. // cell format settings.
  566. func setFills(style *xlsxStyleSheet, formatCellStyle *formatCellStyle) int {
  567. var patterns = []string{
  568. "none",
  569. "solid",
  570. "mediumGray",
  571. "darkGray",
  572. "lightGray",
  573. "darkHorizontal",
  574. "darkVertical",
  575. "darkDown",
  576. "darkUp",
  577. "darkGrid",
  578. "darkTrellis",
  579. "lightHorizontal",
  580. "lightVertical",
  581. "lightDown",
  582. "lightUp",
  583. "lightGrid",
  584. "lightTrellis",
  585. "gray125",
  586. "gray0625",
  587. }
  588. var variants = []float64{
  589. 90,
  590. 0,
  591. 45,
  592. 135,
  593. }
  594. var fill xlsxFill
  595. switch formatCellStyle.Fill.Type {
  596. case "gradient":
  597. if len(formatCellStyle.Fill.Color) != 2 {
  598. break
  599. }
  600. var gradient xlsxGradientFill
  601. switch formatCellStyle.Fill.Shading {
  602. case 0, 1, 2, 3:
  603. gradient.Degree = variants[formatCellStyle.Fill.Shading]
  604. case 4:
  605. gradient.Type = "path"
  606. case 5:
  607. gradient.Type = "path"
  608. gradient.Bottom = 0.5
  609. gradient.Left = 0.5
  610. gradient.Right = 0.5
  611. gradient.Top = 0.5
  612. default:
  613. break
  614. }
  615. var stops []*xlsxGradientFillStop
  616. for index, color := range formatCellStyle.Fill.Color {
  617. var stop xlsxGradientFillStop
  618. stop.Position = float64(index)
  619. stop.Color.RGB = getPaletteColor(color)
  620. stops = append(stops, &stop)
  621. }
  622. gradient.Stop = stops
  623. fill.GradientFill = &gradient
  624. case "pattern":
  625. if formatCellStyle.Fill.Pattern > 18 || formatCellStyle.Fill.Pattern < 0 {
  626. break
  627. }
  628. if len(formatCellStyle.Fill.Color) < 1 {
  629. break
  630. }
  631. var pattern xlsxPatternFill
  632. pattern.PatternType = patterns[formatCellStyle.Fill.Pattern]
  633. pattern.FgColor.RGB = getPaletteColor(formatCellStyle.Fill.Color[0])
  634. fill.PatternFill = &pattern
  635. }
  636. style.Fills.Count++
  637. style.Fills.Fill = append(style.Fills.Fill, &fill)
  638. return style.Fills.Count - 1
  639. }
  640. // setAlignment provides function to formatting information pertaining to text
  641. // alignment in cells. There are a variety of choices for how text is aligned
  642. // both horizontally and vertically, as well as indentation settings, and so on.
  643. func setAlignment(style *xlsxStyleSheet, formatCellStyle *formatCellStyle) (bool, *xlsxAlignment) {
  644. if formatCellStyle.Alignment == nil {
  645. return false, &xlsxAlignment{}
  646. }
  647. var alignment = xlsxAlignment{
  648. Horizontal: formatCellStyle.Alignment.Horizontal,
  649. Indent: formatCellStyle.Alignment.Indent,
  650. JustifyLastLine: formatCellStyle.Alignment.JustifyLastLine,
  651. ReadingOrder: formatCellStyle.Alignment.ReadingOrder,
  652. RelativeIndent: formatCellStyle.Alignment.RelativeIndent,
  653. ShrinkToFit: formatCellStyle.Alignment.ShrinkToFit,
  654. TextRotation: formatCellStyle.Alignment.TextRotation,
  655. Vertical: formatCellStyle.Alignment.Vertical,
  656. WrapText: formatCellStyle.Alignment.WrapText,
  657. }
  658. return true, &alignment
  659. }
  660. // setBorders provides function to add border elements in the styles.xml by
  661. // given borders format settings.
  662. func setBorders(style *xlsxStyleSheet, formatCellStyle *formatCellStyle) int {
  663. var styles = []string{
  664. "none",
  665. "thin",
  666. "medium",
  667. "dashed",
  668. "dotted",
  669. "thick",
  670. "double",
  671. "hair",
  672. "mediumDashed",
  673. "dashDot",
  674. "mediumDashDot",
  675. "dashDotDot",
  676. "mediumDashDotDot",
  677. "slantDashDot",
  678. }
  679. var border xlsxBorder
  680. for _, v := range formatCellStyle.Border {
  681. if v.Style > 13 || v.Style < 0 {
  682. continue
  683. }
  684. var color xlsxColor
  685. color.RGB = getPaletteColor(v.Color)
  686. switch v.Type {
  687. case "left":
  688. border.Left.Style = styles[v.Style]
  689. border.Left.Color = &color
  690. case "right":
  691. border.Right.Style = styles[v.Style]
  692. border.Right.Color = &color
  693. case "top":
  694. border.Top.Style = styles[v.Style]
  695. border.Top.Color = &color
  696. case "bottom":
  697. border.Bottom.Style = styles[v.Style]
  698. border.Bottom.Color = &color
  699. case "diagonalUp":
  700. border.Diagonal.Style = styles[v.Style]
  701. border.Diagonal.Color = &color
  702. border.DiagonalUp = true
  703. case "diagonalDown":
  704. border.Diagonal.Style = styles[v.Style]
  705. border.Diagonal.Color = &color
  706. border.DiagonalDown = true
  707. }
  708. }
  709. style.Borders.Count++
  710. style.Borders.Border = append(style.Borders.Border, &border)
  711. return style.Borders.Count - 1
  712. }
  713. // setCellXfs provides function to set describes all of the formatting for a
  714. // cell.
  715. func setCellXfs(style *xlsxStyleSheet, fontID, numFmtID, fillID, borderID int, applyAlignment bool, alignment *xlsxAlignment) int {
  716. var xf xlsxXf
  717. xf.FontID = fontID
  718. if fontID != 0 {
  719. xf.ApplyFont = true
  720. }
  721. xf.NumFmtID = numFmtID
  722. if numFmtID != 0 {
  723. xf.ApplyNumberFormat = true
  724. }
  725. xf.FillID = fillID
  726. xf.BorderID = borderID
  727. style.CellXfs.Count++
  728. xf.Alignment = alignment
  729. xf.ApplyAlignment = applyAlignment
  730. style.CellXfs.Xf = append(style.CellXfs.Xf, xf)
  731. return style.CellXfs.Count - 1
  732. }
  733. // setCellStyle provides function to add style attribute for cells by given
  734. // sheet index, coordinate area and style ID.
  735. func (f *File) setCellStyle(sheet, hcell, vcell string, styleID int) {
  736. hcell = strings.ToUpper(hcell)
  737. vcell = strings.ToUpper(vcell)
  738. // Coordinate conversion, convert C1:B3 to 2,0,1,2.
  739. hcol := string(strings.Map(letterOnlyMapF, hcell))
  740. hrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, hcell))
  741. hyAxis := hrow - 1
  742. hxAxis := TitleToNumber(hcol)
  743. vcol := string(strings.Map(letterOnlyMapF, vcell))
  744. vrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, vcell))
  745. vyAxis := vrow - 1
  746. vxAxis := TitleToNumber(vcol)
  747. if vxAxis < hxAxis {
  748. hcell, vcell = vcell, hcell
  749. vxAxis, hxAxis = hxAxis, vxAxis
  750. }
  751. if vyAxis < hyAxis {
  752. hcell, vcell = vcell, hcell
  753. vyAxis, hyAxis = hyAxis, vyAxis
  754. }
  755. // Correct the coordinate area, such correct C1:B3 to B1:C3.
  756. hcell = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1)
  757. vcell = ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
  758. xlsx := f.workSheetReader(sheet)
  759. completeRow(xlsx, vyAxis+1, vxAxis+1)
  760. completeCol(xlsx, vyAxis+1, vxAxis+1)
  761. for r, row := range xlsx.SheetData.Row {
  762. for k, c := range row.C {
  763. if checkCellInArea(c.R, hcell+":"+vcell) {
  764. xlsx.SheetData.Row[r].C[k].S = styleID
  765. }
  766. }
  767. }
  768. }
  769. // getPaletteColor provides function to convert the RBG color by given string.
  770. func getPaletteColor(color string) string {
  771. return "FF" + strings.Replace(strings.ToUpper(color), "#", "", -1)
  772. }