table.go 14 KB

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