table.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /*
  2. Package excelize providing a set of functions that allow you to write to
  3. and read from XLSX files. Support reads and writes XLSX file generated by
  4. Microsoft Excel™ 2007 and later. Support save file without losing original
  5. charts of XLSX. This library needs Go version 1.8 or later.
  6. Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
  7. this source code is governed by a BSD-style license that can be found in
  8. the LICENSE file.
  9. */
  10. package excelize
  11. import (
  12. "encoding/json"
  13. "encoding/xml"
  14. "fmt"
  15. "regexp"
  16. "strconv"
  17. "strings"
  18. )
  19. // parseFormatTableSet provides a function to parse the format settings of the
  20. // table with default value.
  21. func parseFormatTableSet(formatSet string) (*formatTable, error) {
  22. format := formatTable{
  23. TableStyle: "",
  24. ShowRowStripes: true,
  25. }
  26. err := json.Unmarshal(parseFormatSet(formatSet), &format)
  27. return &format, err
  28. }
  29. // AddTable provides the method to add table in a worksheet by given worksheet
  30. // name, coordinate area and format set. For example, create a table of A1:D5
  31. // on Sheet1:
  32. //
  33. // xlsx.AddTable("Sheet1", "A1", "D5", ``)
  34. //
  35. // Create a table of F2:H6 on Sheet2 with format set:
  36. //
  37. // xlsx.AddTable("Sheet2", "F2", "H6", `{"table_name":"table","table_style":"TableStyleMedium2", "show_first_column":true,"show_last_column":true,"show_row_stripes":false,"show_column_stripes":true}`)
  38. //
  39. // Note that the table at least two lines include string type header. Multiple
  40. // tables coordinate areas can't have an intersection.
  41. //
  42. // table_name: The name of the table, in the same worksheet name of the table should be unique
  43. //
  44. // table_style: The built-in table style names
  45. //
  46. // TableStyleLight1 - TableStyleLight21
  47. // TableStyleMedium1 - TableStyleMedium28
  48. // TableStyleDark1 - TableStyleDark11
  49. //
  50. func (f *File) AddTable(sheet, hcell, vcell, format string) error {
  51. formatSet, err := parseFormatTableSet(format)
  52. if err != nil {
  53. return err
  54. }
  55. hcell = strings.ToUpper(hcell)
  56. vcell = strings.ToUpper(vcell)
  57. // Coordinate conversion, convert C1:B3 to 2,0,1,2.
  58. hcol := string(strings.Map(letterOnlyMapF, hcell))
  59. hrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, hcell))
  60. hyAxis := hrow - 1
  61. hxAxis := TitleToNumber(hcol)
  62. vcol := string(strings.Map(letterOnlyMapF, vcell))
  63. vrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, vcell))
  64. vyAxis := vrow - 1
  65. vxAxis := TitleToNumber(vcol)
  66. if vxAxis < hxAxis {
  67. vxAxis, hxAxis = hxAxis, vxAxis
  68. }
  69. if vyAxis < hyAxis {
  70. vyAxis, hyAxis = hyAxis, vyAxis
  71. }
  72. tableID := f.countTables() + 1
  73. sheetRelationshipsTableXML := "../tables/table" + strconv.Itoa(tableID) + ".xml"
  74. tableXML := strings.Replace(sheetRelationshipsTableXML, "..", "xl", -1)
  75. // Add first table for given sheet.
  76. rID := f.addSheetRelationships(sheet, SourceRelationshipTable, sheetRelationshipsTableXML, "")
  77. f.addSheetTable(sheet, rID)
  78. f.addTable(sheet, tableXML, hxAxis, hyAxis, vxAxis, vyAxis, tableID, formatSet)
  79. f.addContentTypePart(tableID, "table")
  80. return err
  81. }
  82. // countTables provides a function to get table files count storage in the
  83. // folder xl/tables.
  84. func (f *File) countTables() int {
  85. count := 0
  86. for k := range f.XLSX {
  87. if strings.Contains(k, "xl/tables/table") {
  88. count++
  89. }
  90. }
  91. return count
  92. }
  93. // addSheetTable provides a function to add tablePart element to
  94. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  95. func (f *File) addSheetTable(sheet string, rID int) {
  96. xlsx := f.workSheetReader(sheet)
  97. table := &xlsxTablePart{
  98. RID: "rId" + strconv.Itoa(rID),
  99. }
  100. if xlsx.TableParts == nil {
  101. xlsx.TableParts = &xlsxTableParts{}
  102. }
  103. xlsx.TableParts.Count++
  104. xlsx.TableParts.TableParts = append(xlsx.TableParts.TableParts, table)
  105. }
  106. // addTable provides a function to add table by given worksheet name,
  107. // coordinate area and format set.
  108. func (f *File) addTable(sheet, tableXML string, hxAxis, hyAxis, vxAxis, vyAxis, i int, formatSet *formatTable) {
  109. // Correct the minimum number of rows, the table at least two lines.
  110. if hyAxis == vyAxis {
  111. vyAxis++
  112. }
  113. // Correct table reference coordinate area, such correct C1:B3 to B1:C3.
  114. ref := ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
  115. tableColumn := []*xlsxTableColumn{}
  116. idx := 0
  117. for i := hxAxis; i <= vxAxis; i++ {
  118. idx++
  119. cell := ToAlphaString(i) + strconv.Itoa(hyAxis+1)
  120. name := f.GetCellValue(sheet, cell)
  121. if _, err := strconv.Atoi(name); err == nil {
  122. f.SetCellStr(sheet, cell, name)
  123. }
  124. if name == "" {
  125. name = "Column" + strconv.Itoa(idx)
  126. f.SetCellStr(sheet, cell, name)
  127. }
  128. tableColumn = append(tableColumn, &xlsxTableColumn{
  129. ID: idx,
  130. Name: name,
  131. })
  132. }
  133. name := formatSet.TableName
  134. if name == "" {
  135. name = "Table" + strconv.Itoa(i)
  136. }
  137. t := xlsxTable{
  138. XMLNS: NameSpaceSpreadSheet,
  139. ID: i,
  140. Name: name,
  141. DisplayName: name,
  142. Ref: ref,
  143. AutoFilter: &xlsxAutoFilter{
  144. Ref: ref,
  145. },
  146. TableColumns: &xlsxTableColumns{
  147. Count: idx,
  148. TableColumn: tableColumn,
  149. },
  150. TableStyleInfo: &xlsxTableStyleInfo{
  151. Name: formatSet.TableStyle,
  152. ShowFirstColumn: formatSet.ShowFirstColumn,
  153. ShowLastColumn: formatSet.ShowLastColumn,
  154. ShowRowStripes: formatSet.ShowRowStripes,
  155. ShowColumnStripes: formatSet.ShowColumnStripes,
  156. },
  157. }
  158. table, _ := xml.Marshal(t)
  159. f.saveFileList(tableXML, table)
  160. }
  161. // parseAutoFilterSet provides a function to parse the settings of the auto
  162. // filter.
  163. func parseAutoFilterSet(formatSet string) (*formatAutoFilter, error) {
  164. format := formatAutoFilter{}
  165. err := json.Unmarshal([]byte(formatSet), &format)
  166. return &format, err
  167. }
  168. // AutoFilter provides the method to add auto filter in a worksheet by given
  169. // worksheet name, coordinate area and settings. An autofilter in Excel is a
  170. // way of filtering a 2D range of data based on some simple criteria. For
  171. // example applying an autofilter to a cell range A1:D4 in the Sheet1:
  172. //
  173. // err = xlsx.AutoFilter("Sheet1", "A1", "D4", "")
  174. //
  175. // Filter data in an autofilter:
  176. //
  177. // err = xlsx.AutoFilter("Sheet1", "A1", "D4", `{"column":"B","expression":"x != blanks"}`)
  178. //
  179. // column defines the filter columns in a autofilter range based on simple
  180. // criteria
  181. //
  182. // It isn't sufficient to just specify the filter condition. You must also
  183. // hide any rows that don't match the filter condition. Rows are hidden using
  184. // the SetRowVisible() method. Excelize can't filter rows automatically since
  185. // this isn't part of the file format.
  186. //
  187. // Setting a filter criteria for a column:
  188. //
  189. // expression defines the conditions, the following operators are available
  190. // for setting the filter criteria:
  191. //
  192. // ==
  193. // !=
  194. // >
  195. // <
  196. // >=
  197. // <=
  198. // and
  199. // or
  200. //
  201. // An expression can comprise a single statement or two statements separated
  202. // by the 'and' and 'or' operators. For example:
  203. //
  204. // x < 2000
  205. // x > 2000
  206. // x == 2000
  207. // x > 2000 and x < 5000
  208. // x == 2000 or x == 5000
  209. //
  210. // Filtering of blank or non-blank data can be achieved by using a value of
  211. // Blanks or NonBlanks in the expression:
  212. //
  213. // x == Blanks
  214. // x == NonBlanks
  215. //
  216. // Excel also allows some simple string matching operations:
  217. //
  218. // x == b* // begins with b
  219. // x != b* // doesnt begin with b
  220. // x == *b // ends with b
  221. // x != *b // doesnt end with b
  222. // x == *b* // contains b
  223. // x != *b* // doesn't contains b
  224. //
  225. // You can also use '*' to match any character or number and '?' to match any
  226. // single character or number. No other regular expression quantifier is
  227. // supported by Excel's filters. Excel's regular expression characters can be
  228. // escaped using '~'.
  229. //
  230. // The placeholder variable x in the above examples can be replaced by any
  231. // simple string. The actual placeholder name is ignored internally so the
  232. // following are all equivalent:
  233. //
  234. // x < 2000
  235. // col < 2000
  236. // Price < 2000
  237. //
  238. func (f *File) AutoFilter(sheet, hcell, vcell, format string) error {
  239. formatSet, _ := parseAutoFilterSet(format)
  240. hcell = strings.ToUpper(hcell)
  241. vcell = strings.ToUpper(vcell)
  242. // Coordinate conversion, convert C1:B3 to 2,0,1,2.
  243. hcol := string(strings.Map(letterOnlyMapF, hcell))
  244. hrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, hcell))
  245. hyAxis := hrow - 1
  246. hxAxis := TitleToNumber(hcol)
  247. vcol := string(strings.Map(letterOnlyMapF, vcell))
  248. vrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, vcell))
  249. vyAxis := vrow - 1
  250. vxAxis := TitleToNumber(vcol)
  251. if vxAxis < hxAxis {
  252. vxAxis, hxAxis = hxAxis, vxAxis
  253. }
  254. if vyAxis < hyAxis {
  255. vyAxis, hyAxis = hyAxis, vyAxis
  256. }
  257. ref := ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
  258. refRange := vxAxis - hxAxis
  259. return f.autoFilter(sheet, ref, refRange, hxAxis, formatSet)
  260. }
  261. // autoFilter provides a function to extract the tokens from the filter
  262. // expression. The tokens are mainly non-whitespace groups.
  263. func (f *File) autoFilter(sheet, ref string, refRange, hxAxis int, formatSet *formatAutoFilter) error {
  264. xlsx := f.workSheetReader(sheet)
  265. if xlsx.SheetPr != nil {
  266. xlsx.SheetPr.FilterMode = true
  267. }
  268. xlsx.SheetPr = &xlsxSheetPr{FilterMode: true}
  269. filter := &xlsxAutoFilter{
  270. Ref: ref,
  271. }
  272. xlsx.AutoFilter = filter
  273. if formatSet.Column == "" || formatSet.Expression == "" {
  274. return nil
  275. }
  276. col := TitleToNumber(formatSet.Column)
  277. offset := col - hxAxis
  278. if offset < 0 || offset > refRange {
  279. return fmt.Errorf("incorrect index of column '%s'", formatSet.Column)
  280. }
  281. filter.FilterColumn = &xlsxFilterColumn{
  282. ColID: offset,
  283. }
  284. re := regexp.MustCompile(`"(?:[^"]|"")*"|\S+`)
  285. token := re.FindAllString(formatSet.Expression, -1)
  286. if len(token) != 3 && len(token) != 7 {
  287. return fmt.Errorf("incorrect number of tokens in criteria '%s'", formatSet.Expression)
  288. }
  289. expressions, tokens, err := f.parseFilterExpression(formatSet.Expression, token)
  290. if err != nil {
  291. return err
  292. }
  293. f.writeAutoFilter(filter, expressions, tokens)
  294. xlsx.AutoFilter = filter
  295. return nil
  296. }
  297. // writeAutoFilter provides a function to check for single or double custom
  298. // filters as default filters and handle them accordingly.
  299. func (f *File) writeAutoFilter(filter *xlsxAutoFilter, exp []int, tokens []string) {
  300. if len(exp) == 1 && exp[0] == 2 {
  301. // Single equality.
  302. filters := []*xlsxFilter{}
  303. filters = append(filters, &xlsxFilter{Val: tokens[0]})
  304. filter.FilterColumn.Filters = &xlsxFilters{Filter: filters}
  305. } else if len(exp) == 3 && exp[0] == 2 && exp[1] == 1 && exp[2] == 2 {
  306. // Double equality with "or" operator.
  307. filters := []*xlsxFilter{}
  308. for _, v := range tokens {
  309. filters = append(filters, &xlsxFilter{Val: v})
  310. }
  311. filter.FilterColumn.Filters = &xlsxFilters{Filter: filters}
  312. } else {
  313. // Non default custom filter.
  314. expRel := map[int]int{0: 0, 1: 2}
  315. andRel := map[int]bool{0: true, 1: false}
  316. for k, v := range tokens {
  317. f.writeCustomFilter(filter, exp[expRel[k]], v)
  318. if k == 1 {
  319. filter.FilterColumn.CustomFilters.And = andRel[exp[k]]
  320. }
  321. }
  322. }
  323. }
  324. // writeCustomFilter provides a function to write the <customFilter> element.
  325. func (f *File) writeCustomFilter(filter *xlsxAutoFilter, operator int, val string) {
  326. operators := map[int]string{
  327. 1: "lessThan",
  328. 2: "equal",
  329. 3: "lessThanOrEqual",
  330. 4: "greaterThan",
  331. 5: "notEqual",
  332. 6: "greaterThanOrEqual",
  333. 22: "equal",
  334. }
  335. customFilter := xlsxCustomFilter{
  336. Operator: operators[operator],
  337. Val: val,
  338. }
  339. if filter.FilterColumn.CustomFilters != nil {
  340. filter.FilterColumn.CustomFilters.CustomFilter = append(filter.FilterColumn.CustomFilters.CustomFilter, &customFilter)
  341. } else {
  342. customFilters := []*xlsxCustomFilter{}
  343. customFilters = append(customFilters, &customFilter)
  344. filter.FilterColumn.CustomFilters = &xlsxCustomFilters{CustomFilter: customFilters}
  345. }
  346. }
  347. // parseFilterExpression provides a function to converts the tokens of a
  348. // possibly conditional expression into 1 or 2 sub expressions for further
  349. // parsing.
  350. //
  351. // Examples:
  352. //
  353. // ('x', '==', 2000) -> exp1
  354. // ('x', '>', 2000, 'and', 'x', '<', 5000) -> exp1 and exp2
  355. //
  356. func (f *File) parseFilterExpression(expression string, tokens []string) ([]int, []string, error) {
  357. expressions := []int{}
  358. t := []string{}
  359. if len(tokens) == 7 {
  360. // The number of tokens will be either 3 (for 1 expression) or 7 (for 2
  361. // expressions).
  362. conditional := 0
  363. c := tokens[3]
  364. re, _ := regexp.Match(`(or|\|\|)`, []byte(c))
  365. if re {
  366. conditional = 1
  367. }
  368. expression1, token1, err := f.parseFilterTokens(expression, tokens[0:3])
  369. if err != nil {
  370. return expressions, t, err
  371. }
  372. expression2, token2, err := f.parseFilterTokens(expression, tokens[4:7])
  373. if err != nil {
  374. return expressions, t, err
  375. }
  376. expressions = []int{expression1[0], conditional, expression2[0]}
  377. t = []string{token1, token2}
  378. } else {
  379. exp, token, err := f.parseFilterTokens(expression, tokens)
  380. if err != nil {
  381. return expressions, t, err
  382. }
  383. expressions = exp
  384. t = []string{token}
  385. }
  386. return expressions, t, nil
  387. }
  388. // parseFilterTokens provides a function to parse the 3 tokens of a filter
  389. // expression and return the operator and token.
  390. func (f *File) parseFilterTokens(expression string, tokens []string) ([]int, string, error) {
  391. operators := map[string]int{
  392. "==": 2,
  393. "=": 2,
  394. "=~": 2,
  395. "eq": 2,
  396. "!=": 5,
  397. "!~": 5,
  398. "ne": 5,
  399. "<>": 5,
  400. "<": 1,
  401. "<=": 3,
  402. ">": 4,
  403. ">=": 6,
  404. }
  405. operator, ok := operators[strings.ToLower(tokens[1])]
  406. if !ok {
  407. // Convert the operator from a number to a descriptive string.
  408. return []int{}, "", fmt.Errorf("unknown operator: %s", tokens[1])
  409. }
  410. token := tokens[2]
  411. // Special handling for Blanks/NonBlanks.
  412. re, _ := regexp.Match("blanks|nonblanks", []byte(strings.ToLower(token)))
  413. if re {
  414. // Only allow Equals or NotEqual in this context.
  415. if operator != 2 && operator != 5 {
  416. return []int{operator}, token, fmt.Errorf("the operator '%s' in expression '%s' is not valid in relation to Blanks/NonBlanks'", tokens[1], expression)
  417. }
  418. token = strings.ToLower(token)
  419. // The operator should always be 2 (=) to flag a "simple" equality in
  420. // the binary record. Therefore we convert <> to =.
  421. if token == "blanks" {
  422. if operator == 5 {
  423. token = " "
  424. }
  425. } else {
  426. if operator == 5 {
  427. operator = 2
  428. token = "blanks"
  429. } else {
  430. operator = 5
  431. token = " "
  432. }
  433. }
  434. }
  435. // if the string token contains an Excel match character then change the
  436. // operator type to indicate a non "simple" equality.
  437. re, _ = regexp.Match("[*?]", []byte(token))
  438. if operator == 2 && re {
  439. operator = 22
  440. }
  441. return []int{operator}, token, nil
  442. }