table.go 16 KB

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