table.go 14 KB

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