table.go 15 KB

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