pivotTable.go 13 KB

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