pivotTable.go 21 KB

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