table.go 15 KB

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