table.go 14 KB

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