table.go 14 KB

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