pivotTable.go 21 KB

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