table.go 14 KB

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