table.go 14 KB

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