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