table.go 14 KB

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