table.go 14 KB

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