table.go 14 KB

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