pivotTable.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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 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/xml"
  14. "errors"
  15. "fmt"
  16. "strconv"
  17. "strings"
  18. )
  19. // PivotTableOption directly maps the format settings of the pivot table.
  20. type PivotTableOption struct {
  21. DataRange string
  22. PivotTableRange string
  23. Rows []PivotTableField
  24. Columns []PivotTableField
  25. Data []PivotTableField
  26. Filter []PivotTableField
  27. RowGrandTotals bool
  28. ColGrandTotals bool
  29. ShowDrill bool
  30. UseAutoFormatting bool
  31. PageOverThenDown bool
  32. MergeItem bool
  33. CompactData bool
  34. ShowRowHeaders bool
  35. ShowColHeaders bool
  36. ShowRowStripes bool
  37. ShowColStripes bool
  38. ShowLastColumn bool
  39. PivotTableStyleName string
  40. }
  41. // PivotTableField directly maps the field settings of the pivot table.
  42. // Subtotal specifies the aggregation function that applies to this data
  43. // field. The default value is sum. The possible values for this attribute
  44. // are:
  45. //
  46. // Average
  47. // Count
  48. // CountNums
  49. // Max
  50. // Min
  51. // Product
  52. // StdDev
  53. // StdDevp
  54. // Sum
  55. // Var
  56. // Varp
  57. //
  58. // Name specifies the name of the data field. Maximum 255 characters
  59. // are allowed in data field name, excess characters will be truncated.
  60. type PivotTableField struct {
  61. Data string
  62. Name string
  63. Subtotal string
  64. DefaultSubtotal bool
  65. }
  66. // AddPivotTable provides the method to add pivot table by given pivot table
  67. // options.
  68. //
  69. // For example, create a pivot table on the Sheet1!$G$2:$M$34 area with the
  70. // region Sheet1!$A$1:$E$31 as the data source, summarize by sum for sales:
  71. //
  72. // package main
  73. //
  74. // import (
  75. // "fmt"
  76. // "math/rand"
  77. //
  78. // "github.com/360EntSecGroup-Skylar/excelize/v2"
  79. // )
  80. //
  81. // func main() {
  82. // f := excelize.NewFile()
  83. // // Create some data in a sheet
  84. // month := []string{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
  85. // year := []int{2017, 2018, 2019}
  86. // types := []string{"Meat", "Dairy", "Beverages", "Produce"}
  87. // region := []string{"East", "West", "North", "South"}
  88. // f.SetSheetRow("Sheet1", "A1", &[]string{"Month", "Year", "Type", "Sales", "Region"})
  89. // for i := 0; i < 30; i++ {
  90. // f.SetCellValue("Sheet1", fmt.Sprintf("A%d", i+2), month[rand.Intn(12)])
  91. // f.SetCellValue("Sheet1", fmt.Sprintf("B%d", i+2), year[rand.Intn(3)])
  92. // f.SetCellValue("Sheet1", fmt.Sprintf("C%d", i+2), types[rand.Intn(4)])
  93. // f.SetCellValue("Sheet1", fmt.Sprintf("D%d", i+2), rand.Intn(5000))
  94. // f.SetCellValue("Sheet1", fmt.Sprintf("E%d", i+2), region[rand.Intn(4)])
  95. // }
  96. // if err := f.AddPivotTable(&excelize.PivotTableOption{
  97. // DataRange: "Sheet1!$A$1:$E$31",
  98. // PivotTableRange: "Sheet1!$G$2:$M$34",
  99. // Rows: []excelize.PivotTableField{{Data: "Month", DefaultSubtotal: true}, {Data: "Year"}},
  100. // Filter: []excelize.PivotTableField{{Data: "Region"}},
  101. // Columns: []excelize.PivotTableField{{Data: "Type", DefaultSubtotal: true}},
  102. // Data: []excelize.PivotTableField{{Data: "Sales", Name: "Summarize", Subtotal: "Sum"}},
  103. // RowGrandTotals: true,
  104. // ColGrandTotals: true,
  105. // ShowDrill: true,
  106. // ShowRowHeaders: true,
  107. // ShowColHeaders: true,
  108. // ShowLastColumn: true,
  109. // }); err != nil {
  110. // fmt.Println(err)
  111. // }
  112. // if err := f.SaveAs("Book1.xlsx"); err != nil {
  113. // fmt.Println(err)
  114. // }
  115. // }
  116. //
  117. func (f *File) AddPivotTable(opt *PivotTableOption) error {
  118. // parameter validation
  119. dataSheet, pivotTableSheetPath, err := f.parseFormatPivotTableSet(opt)
  120. if err != nil {
  121. return err
  122. }
  123. pivotTableID := f.countPivotTables() + 1
  124. pivotCacheID := f.countPivotCache() + 1
  125. sheetRelationshipsPivotTableXML := "../pivotTables/pivotTable" + strconv.Itoa(pivotTableID) + ".xml"
  126. pivotTableXML := strings.Replace(sheetRelationshipsPivotTableXML, "..", "xl", -1)
  127. pivotCacheXML := "xl/pivotCache/pivotCacheDefinition" + strconv.Itoa(pivotCacheID) + ".xml"
  128. err = f.addPivotCache(pivotCacheID, pivotCacheXML, opt, dataSheet)
  129. if err != nil {
  130. return err
  131. }
  132. // workbook pivot cache
  133. workBookPivotCacheRID := f.addRels(f.getWorkbookRelsPath(), SourceRelationshipPivotCache, fmt.Sprintf("/xl/pivotCache/pivotCacheDefinition%d.xml", pivotCacheID), "")
  134. cacheID := f.addWorkbookPivotCache(workBookPivotCacheRID)
  135. pivotCacheRels := "xl/pivotTables/_rels/pivotTable" + strconv.Itoa(pivotTableID) + ".xml.rels"
  136. // rId not used
  137. _ = f.addRels(pivotCacheRels, SourceRelationshipPivotCache, fmt.Sprintf("../pivotCache/pivotCacheDefinition%d.xml", pivotCacheID), "")
  138. err = f.addPivotTable(cacheID, pivotTableID, pivotTableXML, opt)
  139. if err != nil {
  140. return err
  141. }
  142. pivotTableSheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(pivotTableSheetPath, "xl/worksheets/") + ".rels"
  143. f.addRels(pivotTableSheetRels, SourceRelationshipPivotTable, sheetRelationshipsPivotTableXML, "")
  144. f.addContentTypePart(pivotTableID, "pivotTable")
  145. f.addContentTypePart(pivotCacheID, "pivotCache")
  146. return nil
  147. }
  148. // parseFormatPivotTableSet provides a function to validate pivot table
  149. // properties.
  150. func (f *File) parseFormatPivotTableSet(opt *PivotTableOption) (*xlsxWorksheet, string, error) {
  151. if opt == nil {
  152. return nil, "", errors.New("parameter is required")
  153. }
  154. dataSheetName, _, err := f.adjustRange(opt.DataRange)
  155. if err != nil {
  156. return nil, "", fmt.Errorf("parameter 'DataRange' parsing error: %s", err.Error())
  157. }
  158. pivotTableSheetName, _, err := f.adjustRange(opt.PivotTableRange)
  159. if err != nil {
  160. return nil, "", fmt.Errorf("parameter 'PivotTableRange' parsing error: %s", err.Error())
  161. }
  162. dataSheet, err := f.workSheetReader(dataSheetName)
  163. if err != nil {
  164. return dataSheet, "", err
  165. }
  166. pivotTableSheetPath, ok := f.sheetMap[trimSheetName(pivotTableSheetName)]
  167. if !ok {
  168. return dataSheet, pivotTableSheetPath, fmt.Errorf("sheet %s is not exist", pivotTableSheetName)
  169. }
  170. return dataSheet, pivotTableSheetPath, err
  171. }
  172. // adjustRange adjust range, for example: adjust Sheet1!$E$31:$A$1 to Sheet1!$A$1:$E$31
  173. func (f *File) adjustRange(rangeStr string) (string, []int, error) {
  174. if len(rangeStr) < 1 {
  175. return "", []int{}, errors.New("parameter is required")
  176. }
  177. rng := strings.Split(rangeStr, "!")
  178. if len(rng) != 2 {
  179. return "", []int{}, errors.New("parameter is invalid")
  180. }
  181. trimRng := strings.Replace(rng[1], "$", "", -1)
  182. coordinates, err := f.areaRefToCoordinates(trimRng)
  183. if err != nil {
  184. return rng[0], []int{}, err
  185. }
  186. x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
  187. if x1 == x2 && y1 == y2 {
  188. return rng[0], []int{}, errors.New("parameter is invalid")
  189. }
  190. // Correct the coordinate area, such correct C1:B3 to B1:C3.
  191. if x2 < x1 {
  192. x1, x2 = x2, x1
  193. }
  194. if y2 < y1 {
  195. y1, y2 = y2, y1
  196. }
  197. return rng[0], []int{x1, y1, x2, y2}, nil
  198. }
  199. // getPivotFieldsOrder provides a function to get order list of pivot table
  200. // fields.
  201. func (f *File) getPivotFieldsOrder(dataRange string) ([]string, error) {
  202. order := []string{}
  203. dataSheet, coordinates, err := f.adjustRange(dataRange)
  204. if err != nil {
  205. return order, fmt.Errorf("parameter 'DataRange' parsing error: %s", err.Error())
  206. }
  207. for col := coordinates[0]; col <= coordinates[2]; col++ {
  208. coordinate, _ := CoordinatesToCellName(col, coordinates[1])
  209. name, err := f.GetCellValue(dataSheet, coordinate)
  210. if err != nil {
  211. return order, err
  212. }
  213. order = append(order, name)
  214. }
  215. return order, nil
  216. }
  217. // addPivotCache provides a function to create a pivot cache by given properties.
  218. func (f *File) addPivotCache(pivotCacheID int, pivotCacheXML string, opt *PivotTableOption, ws *xlsxWorksheet) error {
  219. // validate data range
  220. dataSheet, coordinates, err := f.adjustRange(opt.DataRange)
  221. if err != nil {
  222. return fmt.Errorf("parameter 'DataRange' parsing error: %s", err.Error())
  223. }
  224. // data range has been checked
  225. order, _ := f.getPivotFieldsOrder(opt.DataRange)
  226. hcell, _ := CoordinatesToCellName(coordinates[0], coordinates[1])
  227. vcell, _ := CoordinatesToCellName(coordinates[2], coordinates[3])
  228. pc := xlsxPivotCacheDefinition{
  229. SaveData: false,
  230. RefreshOnLoad: true,
  231. CacheSource: &xlsxCacheSource{
  232. Type: "worksheet",
  233. WorksheetSource: &xlsxWorksheetSource{
  234. Ref: hcell + ":" + vcell,
  235. Sheet: dataSheet,
  236. },
  237. },
  238. CacheFields: &xlsxCacheFields{},
  239. }
  240. for _, name := range order {
  241. defaultRowsSubtotal, rowOk := f.getPivotTableFieldNameDefaultSubtotal(name, opt.Rows)
  242. defaultColumnsSubtotal, colOk := f.getPivotTableFieldNameDefaultSubtotal(name, opt.Columns)
  243. sharedItems := xlsxSharedItems{
  244. Count: 0,
  245. }
  246. s := xlsxString{}
  247. if (rowOk && !defaultRowsSubtotal) || (colOk && !defaultColumnsSubtotal) {
  248. s = xlsxString{
  249. V: "",
  250. }
  251. sharedItems.Count++
  252. sharedItems.S = &s
  253. }
  254. pc.CacheFields.CacheField = append(pc.CacheFields.CacheField, &xlsxCacheField{
  255. Name: name,
  256. SharedItems: &sharedItems,
  257. })
  258. }
  259. pc.CacheFields.Count = len(pc.CacheFields.CacheField)
  260. pivotCache, err := xml.Marshal(pc)
  261. f.saveFileList(pivotCacheXML, pivotCache)
  262. return err
  263. }
  264. // addPivotTable provides a function to create a pivot table by given pivot
  265. // table ID and properties.
  266. func (f *File) addPivotTable(cacheID, pivotTableID int, pivotTableXML string, opt *PivotTableOption) error {
  267. // validate pivot table range
  268. _, coordinates, err := f.adjustRange(opt.PivotTableRange)
  269. if err != nil {
  270. return fmt.Errorf("parameter 'PivotTableRange' parsing error: %s", err.Error())
  271. }
  272. hcell, _ := CoordinatesToCellName(coordinates[0], coordinates[1])
  273. vcell, _ := CoordinatesToCellName(coordinates[2], coordinates[3])
  274. pivotTableStyle := func() string {
  275. if opt.PivotTableStyleName == "" {
  276. return "PivotStyleLight16"
  277. }
  278. return opt.PivotTableStyleName
  279. }
  280. pt := xlsxPivotTableDefinition{
  281. Name: fmt.Sprintf("Pivot Table%d", pivotTableID),
  282. CacheID: cacheID,
  283. RowGrandTotals: &opt.RowGrandTotals,
  284. ColGrandTotals: &opt.ColGrandTotals,
  285. ShowDrill: &opt.ShowDrill,
  286. UseAutoFormatting: &opt.UseAutoFormatting,
  287. PageOverThenDown: &opt.PageOverThenDown,
  288. MergeItem: &opt.MergeItem,
  289. CompactData: &opt.CompactData,
  290. DataCaption: "Values",
  291. Location: &xlsxLocation{
  292. Ref: hcell + ":" + vcell,
  293. FirstDataCol: 1,
  294. FirstDataRow: 1,
  295. FirstHeaderRow: 1,
  296. },
  297. PivotFields: &xlsxPivotFields{},
  298. RowItems: &xlsxRowItems{
  299. Count: 1,
  300. I: []*xlsxI{
  301. {
  302. []*xlsxX{{}, {}},
  303. },
  304. },
  305. },
  306. ColItems: &xlsxColItems{
  307. Count: 1,
  308. I: []*xlsxI{{}},
  309. },
  310. PivotTableStyleInfo: &xlsxPivotTableStyleInfo{
  311. Name: pivotTableStyle(),
  312. ShowRowHeaders: opt.ShowRowHeaders,
  313. ShowColHeaders: opt.ShowColHeaders,
  314. ShowRowStripes: opt.ShowRowStripes,
  315. ShowColStripes: opt.ShowColStripes,
  316. ShowLastColumn: opt.ShowLastColumn,
  317. },
  318. }
  319. // pivot fields
  320. _ = f.addPivotFields(&pt, opt)
  321. // count pivot fields
  322. pt.PivotFields.Count = len(pt.PivotFields.PivotField)
  323. // data range has been checked
  324. _ = f.addPivotRowFields(&pt, opt)
  325. _ = f.addPivotColFields(&pt, opt)
  326. _ = f.addPivotPageFields(&pt, opt)
  327. _ = f.addPivotDataFields(&pt, opt)
  328. pivotTable, err := xml.Marshal(pt)
  329. f.saveFileList(pivotTableXML, pivotTable)
  330. return err
  331. }
  332. // addPivotRowFields provides a method to add row fields for pivot table by
  333. // given pivot table options.
  334. func (f *File) addPivotRowFields(pt *xlsxPivotTableDefinition, opt *PivotTableOption) error {
  335. // row fields
  336. rowFieldsIndex, err := f.getPivotFieldsIndex(opt.Rows, opt)
  337. if err != nil {
  338. return err
  339. }
  340. for _, fieldIdx := range rowFieldsIndex {
  341. if pt.RowFields == nil {
  342. pt.RowFields = &xlsxRowFields{}
  343. }
  344. pt.RowFields.Field = append(pt.RowFields.Field, &xlsxField{
  345. X: fieldIdx,
  346. })
  347. }
  348. // count row fields
  349. if pt.RowFields != nil {
  350. pt.RowFields.Count = len(pt.RowFields.Field)
  351. }
  352. return err
  353. }
  354. // addPivotPageFields provides a method to add page fields for pivot table by
  355. // given pivot table options.
  356. func (f *File) addPivotPageFields(pt *xlsxPivotTableDefinition, opt *PivotTableOption) error {
  357. // page fields
  358. pageFieldsIndex, err := f.getPivotFieldsIndex(opt.Filter, opt)
  359. if err != nil {
  360. return err
  361. }
  362. pageFieldsName := f.getPivotTableFieldsName(opt.Filter)
  363. for idx, pageField := range pageFieldsIndex {
  364. if pt.PageFields == nil {
  365. pt.PageFields = &xlsxPageFields{}
  366. }
  367. pt.PageFields.PageField = append(pt.PageFields.PageField, &xlsxPageField{
  368. Name: pageFieldsName[idx],
  369. Fld: pageField,
  370. })
  371. }
  372. // count page fields
  373. if pt.PageFields != nil {
  374. pt.PageFields.Count = len(pt.PageFields.PageField)
  375. }
  376. return err
  377. }
  378. // addPivotDataFields provides a method to add data fields for pivot table by
  379. // given pivot table options.
  380. func (f *File) addPivotDataFields(pt *xlsxPivotTableDefinition, opt *PivotTableOption) error {
  381. // data fields
  382. dataFieldsIndex, err := f.getPivotFieldsIndex(opt.Data, opt)
  383. if err != nil {
  384. return err
  385. }
  386. dataFieldsSubtotals := f.getPivotTableFieldsSubtotal(opt.Data)
  387. dataFieldsName := f.getPivotTableFieldsName(opt.Data)
  388. for idx, dataField := range dataFieldsIndex {
  389. if pt.DataFields == nil {
  390. pt.DataFields = &xlsxDataFields{}
  391. }
  392. pt.DataFields.DataField = append(pt.DataFields.DataField, &xlsxDataField{
  393. Name: dataFieldsName[idx],
  394. Fld: dataField,
  395. Subtotal: dataFieldsSubtotals[idx],
  396. })
  397. }
  398. // count data fields
  399. if pt.DataFields != nil {
  400. pt.DataFields.Count = len(pt.DataFields.DataField)
  401. }
  402. return err
  403. }
  404. // inStrSlice provides a method to check if an element is present in an array,
  405. // and return the index of its location, otherwise return -1.
  406. func inStrSlice(a []string, x string) int {
  407. for idx, n := range a {
  408. if x == n {
  409. return idx
  410. }
  411. }
  412. return -1
  413. }
  414. // inPivotTableField provides a method to check if an element is present in
  415. // pivot table fields list, and return the index of its location, otherwise
  416. // return -1.
  417. func inPivotTableField(a []PivotTableField, x string) int {
  418. for idx, n := range a {
  419. if x == n.Data {
  420. return idx
  421. }
  422. }
  423. return -1
  424. }
  425. // addPivotColFields create pivot column fields by given pivot table
  426. // definition and option.
  427. func (f *File) addPivotColFields(pt *xlsxPivotTableDefinition, opt *PivotTableOption) error {
  428. if len(opt.Columns) == 0 {
  429. if len(opt.Data) <= 1 {
  430. return nil
  431. }
  432. pt.ColFields = &xlsxColFields{}
  433. // in order to create pivot table in case there is no input from Columns
  434. pt.ColFields.Count = 1
  435. pt.ColFields.Field = append(pt.ColFields.Field, &xlsxField{
  436. X: -2,
  437. })
  438. return nil
  439. }
  440. pt.ColFields = &xlsxColFields{}
  441. // col fields
  442. colFieldsIndex, err := f.getPivotFieldsIndex(opt.Columns, opt)
  443. if err != nil {
  444. return err
  445. }
  446. for _, fieldIdx := range colFieldsIndex {
  447. pt.ColFields.Field = append(pt.ColFields.Field, &xlsxField{
  448. X: fieldIdx,
  449. })
  450. }
  451. //in order to create pivot in case there is many Columns and Many Datas
  452. if len(opt.Data) > 1 {
  453. pt.ColFields.Field = append(pt.ColFields.Field, &xlsxField{
  454. X: -2,
  455. })
  456. }
  457. // count col fields
  458. pt.ColFields.Count = len(pt.ColFields.Field)
  459. return err
  460. }
  461. // addPivotFields create pivot fields based on the column order of the first
  462. // row in the data region by given pivot table definition and option.
  463. func (f *File) addPivotFields(pt *xlsxPivotTableDefinition, opt *PivotTableOption) error {
  464. order, err := f.getPivotFieldsOrder(opt.DataRange)
  465. if err != nil {
  466. return err
  467. }
  468. x := 0
  469. for _, name := range order {
  470. if inPivotTableField(opt.Rows, name) != -1 {
  471. defaultSubtotal, ok := f.getPivotTableFieldNameDefaultSubtotal(name, opt.Rows)
  472. var items []*xlsxItem
  473. if !ok || !defaultSubtotal {
  474. items = append(items, &xlsxItem{X: &x})
  475. } else {
  476. items = append(items, &xlsxItem{T: "default"})
  477. }
  478. pt.PivotFields.PivotField = append(pt.PivotFields.PivotField, &xlsxPivotField{
  479. Axis: "axisRow",
  480. Name: f.getPivotTableFieldName(name, opt.Rows),
  481. Items: &xlsxItems{
  482. Count: len(items),
  483. Item: items,
  484. },
  485. DefaultSubtotal: &defaultSubtotal,
  486. })
  487. continue
  488. }
  489. if inPivotTableField(opt.Filter, name) != -1 {
  490. pt.PivotFields.PivotField = append(pt.PivotFields.PivotField, &xlsxPivotField{
  491. Axis: "axisPage",
  492. Name: f.getPivotTableFieldName(name, opt.Columns),
  493. Items: &xlsxItems{
  494. Count: 1,
  495. Item: []*xlsxItem{
  496. {T: "default"},
  497. },
  498. },
  499. })
  500. continue
  501. }
  502. if inPivotTableField(opt.Columns, name) != -1 {
  503. defaultSubtotal, ok := f.getPivotTableFieldNameDefaultSubtotal(name, opt.Columns)
  504. var items []*xlsxItem
  505. if !ok || !defaultSubtotal {
  506. items = append(items, &xlsxItem{X: &x})
  507. } else {
  508. items = append(items, &xlsxItem{T: "default"})
  509. }
  510. pt.PivotFields.PivotField = append(pt.PivotFields.PivotField, &xlsxPivotField{
  511. Axis: "axisCol",
  512. Name: f.getPivotTableFieldName(name, opt.Columns),
  513. Items: &xlsxItems{
  514. Count: len(items),
  515. Item: items,
  516. },
  517. DefaultSubtotal: &defaultSubtotal,
  518. })
  519. continue
  520. }
  521. if inPivotTableField(opt.Data, name) != -1 {
  522. pt.PivotFields.PivotField = append(pt.PivotFields.PivotField, &xlsxPivotField{
  523. DataField: true,
  524. })
  525. continue
  526. }
  527. pt.PivotFields.PivotField = append(pt.PivotFields.PivotField, &xlsxPivotField{})
  528. }
  529. return err
  530. }
  531. // countPivotTables provides a function to get drawing files count storage in
  532. // the folder xl/pivotTables.
  533. func (f *File) countPivotTables() int {
  534. count := 0
  535. for k := range f.XLSX {
  536. if strings.Contains(k, "xl/pivotTables/pivotTable") {
  537. count++
  538. }
  539. }
  540. return count
  541. }
  542. // countPivotCache provides a function to get drawing files count storage in
  543. // the folder xl/pivotCache.
  544. func (f *File) countPivotCache() int {
  545. count := 0
  546. for k := range f.XLSX {
  547. if strings.Contains(k, "xl/pivotCache/pivotCacheDefinition") {
  548. count++
  549. }
  550. }
  551. return count
  552. }
  553. // getPivotFieldsIndex convert the column of the first row in the data region
  554. // to a sequential index by given fields and pivot option.
  555. func (f *File) getPivotFieldsIndex(fields []PivotTableField, opt *PivotTableOption) ([]int, error) {
  556. pivotFieldsIndex := []int{}
  557. orders, err := f.getPivotFieldsOrder(opt.DataRange)
  558. if err != nil {
  559. return pivotFieldsIndex, err
  560. }
  561. for _, field := range fields {
  562. if pos := inStrSlice(orders, field.Data); pos != -1 {
  563. pivotFieldsIndex = append(pivotFieldsIndex, pos)
  564. }
  565. }
  566. return pivotFieldsIndex, nil
  567. }
  568. // getPivotTableFieldsSubtotal prepare fields subtotal by given pivot table fields.
  569. func (f *File) getPivotTableFieldsSubtotal(fields []PivotTableField) []string {
  570. field := make([]string, len(fields))
  571. enums := []string{"average", "count", "countNums", "max", "min", "product", "stdDev", "stdDevp", "sum", "var", "varp"}
  572. inEnums := func(enums []string, val string) string {
  573. for _, enum := range enums {
  574. if strings.EqualFold(enum, val) {
  575. return enum
  576. }
  577. }
  578. return "sum"
  579. }
  580. for idx, fld := range fields {
  581. field[idx] = inEnums(enums, fld.Subtotal)
  582. }
  583. return field
  584. }
  585. // getPivotTableFieldsName prepare fields name list by given pivot table
  586. // fields.
  587. func (f *File) getPivotTableFieldsName(fields []PivotTableField) []string {
  588. field := make([]string, len(fields))
  589. for idx, fld := range fields {
  590. if len(fld.Name) > 255 {
  591. field[idx] = fld.Name[0:255]
  592. continue
  593. }
  594. field[idx] = fld.Name
  595. }
  596. return field
  597. }
  598. // getPivotTableFieldName prepare field name by given pivot table fields.
  599. func (f *File) getPivotTableFieldName(name string, fields []PivotTableField) string {
  600. fieldsName := f.getPivotTableFieldsName(fields)
  601. for idx, field := range fields {
  602. if field.Data == name {
  603. return fieldsName[idx]
  604. }
  605. }
  606. return ""
  607. }
  608. func (f *File) getPivotTableFieldNameDefaultSubtotal(name string, fields []PivotTableField) (bool, bool) {
  609. for _, field := range fields {
  610. if field.Data == name {
  611. return field.DefaultSubtotal, true
  612. }
  613. }
  614. return false, false
  615. }
  616. // addWorkbookPivotCache add the association ID of the pivot cache in workbook.xml.
  617. func (f *File) addWorkbookPivotCache(RID int) int {
  618. wb := f.workbookReader()
  619. if wb.PivotCaches == nil {
  620. wb.PivotCaches = &xlsxPivotCaches{}
  621. }
  622. cacheID := 1
  623. for _, pivotCache := range wb.PivotCaches.PivotCache {
  624. if pivotCache.CacheID > cacheID {
  625. cacheID = pivotCache.CacheID
  626. }
  627. }
  628. cacheID++
  629. wb.PivotCaches.PivotCache = append(wb.PivotCaches.PivotCache, xlsxPivotCache{
  630. CacheID: cacheID,
  631. RID: fmt.Sprintf("rId%d", RID),
  632. })
  633. return cacheID
  634. }