table.go 15 KB

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