pivotTable.go 16 KB

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