picture.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. // Copyright 2016 - 2019 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. "bytes"
  12. "encoding/json"
  13. "encoding/xml"
  14. "errors"
  15. "image"
  16. "io/ioutil"
  17. "os"
  18. "path"
  19. "path/filepath"
  20. "strconv"
  21. "strings"
  22. )
  23. // parseFormatPictureSet provides a function to parse the format settings of
  24. // the picture with default value.
  25. func parseFormatPictureSet(formatSet string) (*formatPicture, error) {
  26. format := formatPicture{
  27. FPrintsWithSheet: true,
  28. FLocksWithSheet: false,
  29. NoChangeAspect: false,
  30. OffsetX: 0,
  31. OffsetY: 0,
  32. XScale: 1.0,
  33. YScale: 1.0,
  34. }
  35. err := json.Unmarshal(parseFormatSet(formatSet), &format)
  36. return &format, err
  37. }
  38. // AddPicture provides the method to add picture in a sheet by given picture
  39. // format set (such as offset, scale, aspect ratio setting and print settings)
  40. // and file path. For example:
  41. //
  42. // package main
  43. //
  44. // import (
  45. // "fmt"
  46. // _ "image/gif"
  47. // _ "image/jpeg"
  48. // _ "image/png"
  49. //
  50. // "github.com/360EntSecGroup-Skylar/excelize"
  51. // )
  52. //
  53. // func main() {
  54. // f := excelize.NewFile()
  55. // // Insert a picture.
  56. // err := f.AddPicture("Sheet1", "A2", "./image1.jpg", "")
  57. // if err != nil {
  58. // fmt.Println(err)
  59. // }
  60. // // Insert a picture scaling in the cell with location hyperlink.
  61. // err = f.AddPicture("Sheet1", "D2", "./image1.png", `{"x_scale": 0.5, "y_scale": 0.5, "hyperlink": "#Sheet2!D8", "hyperlink_type": "Location"}`)
  62. // if err != nil {
  63. // fmt.Println(err)
  64. // }
  65. // // Insert a picture offset in the cell with external hyperlink, printing and positioning support.
  66. // err = f.AddPicture("Sheet1", "H2", "./image3.gif", `{"x_offset": 15, "y_offset": 10, "hyperlink": "https://github.com/360EntSecGroup-Skylar/excelize", "hyperlink_type": "External", "print_obj": true, "lock_aspect_ratio": false, "locked": false, "positioning": "oneCell"}`)
  67. // if err != nil {
  68. // fmt.Println(err)
  69. // }
  70. // err = f.SaveAs("./Book1.xlsx")
  71. // if err != nil {
  72. // fmt.Println(err)
  73. // }
  74. // }
  75. //
  76. // LinkType defines two types of hyperlink "External" for web site or
  77. // "Location" for moving to one of cell in this workbook. When the
  78. // "hyperlink_type" is "Location", coordinates need to start with "#".
  79. //
  80. // Positioning defines two types of the position of a picture in an Excel
  81. // spreadsheet, "oneCell" (Move but don't size with cells) or "absolute"
  82. // (Don't move or size with cells). If you don't set this parameter, default
  83. // positioning is move and size with cells.
  84. func (f *File) AddPicture(sheet, cell, picture, format string) error {
  85. var err error
  86. // Check picture exists first.
  87. if _, err = os.Stat(picture); os.IsNotExist(err) {
  88. return err
  89. }
  90. ext, ok := supportImageTypes[path.Ext(picture)]
  91. if !ok {
  92. return errors.New("unsupported image extension")
  93. }
  94. file, _ := ioutil.ReadFile(picture)
  95. _, name := filepath.Split(picture)
  96. return f.AddPictureFromBytes(sheet, cell, format, name, ext, file)
  97. }
  98. // AddPictureFromBytes provides the method to add picture in a sheet by given
  99. // picture format set (such as offset, scale, aspect ratio setting and print
  100. // settings), file base name, extension name and file bytes. For example:
  101. //
  102. // package main
  103. //
  104. // import (
  105. // "fmt"
  106. // _ "image/jpeg"
  107. // "io/ioutil"
  108. //
  109. // "github.com/360EntSecGroup-Skylar/excelize"
  110. // )
  111. //
  112. // func main() {
  113. // f := excelize.NewFile()
  114. //
  115. // file, err := ioutil.ReadFile("./image1.jpg")
  116. // if err != nil {
  117. // fmt.Println(err)
  118. // }
  119. // err = f.AddPictureFromBytes("Sheet1", "A2", "", "Excel Logo", ".jpg", file)
  120. // if err != nil {
  121. // fmt.Println(err)
  122. // }
  123. // err = f.SaveAs("./Book1.xlsx")
  124. // if err != nil {
  125. // fmt.Println(err)
  126. // }
  127. // }
  128. //
  129. func (f *File) AddPictureFromBytes(sheet, cell, format, name, extension string, file []byte) error {
  130. var drawingHyperlinkRID int
  131. var hyperlinkType string
  132. ext, ok := supportImageTypes[extension]
  133. if !ok {
  134. return errors.New("unsupported image extension")
  135. }
  136. formatSet, err := parseFormatPictureSet(format)
  137. if err != nil {
  138. return err
  139. }
  140. img, _, err := image.DecodeConfig(bytes.NewReader(file))
  141. if err != nil {
  142. return err
  143. }
  144. // Read sheet data.
  145. xlsx, err := f.workSheetReader(sheet)
  146. if err != nil {
  147. return err
  148. }
  149. // Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
  150. drawingID := f.countDrawings() + 1
  151. drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  152. drawingID, drawingXML = f.prepareDrawing(xlsx, drawingID, sheet, drawingXML)
  153. drawingRels := "xl/drawings/_rels/drawing" + strconv.Itoa(drawingID) + ".xml.rels"
  154. mediaStr := ".." + strings.TrimPrefix(f.addMedia(file, ext), "xl")
  155. drawingRID := f.addRels(drawingRels, SourceRelationshipImage, mediaStr, hyperlinkType)
  156. // Add picture with hyperlink.
  157. if formatSet.Hyperlink != "" && formatSet.HyperlinkType != "" {
  158. if formatSet.HyperlinkType == "External" {
  159. hyperlinkType = formatSet.HyperlinkType
  160. }
  161. drawingHyperlinkRID = f.addRels(drawingRels, SourceRelationshipHyperLink, formatSet.Hyperlink, hyperlinkType)
  162. }
  163. err = f.addDrawingPicture(sheet, drawingXML, cell, name, img.Width, img.Height, drawingRID, drawingHyperlinkRID, formatSet)
  164. if err != nil {
  165. return err
  166. }
  167. f.addContentTypePart(drawingID, "drawings")
  168. return err
  169. }
  170. // deleteSheetRelationships provides a function to delete relationships in
  171. // xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
  172. // relationship index.
  173. func (f *File) deleteSheetRelationships(sheet, rID string) {
  174. name, ok := f.sheetMap[trimSheetName(sheet)]
  175. if !ok {
  176. name = strings.ToLower(sheet) + ".xml"
  177. }
  178. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  179. sheetRels := f.relsReader(rels)
  180. if sheetRels == nil {
  181. sheetRels = &xlsxRelationships{}
  182. }
  183. for k, v := range sheetRels.Relationships {
  184. if v.ID == rID {
  185. sheetRels.Relationships = append(sheetRels.Relationships[:k], sheetRels.Relationships[k+1:]...)
  186. }
  187. }
  188. f.Relationships[rels] = sheetRels
  189. }
  190. // addSheetLegacyDrawing provides a function to add legacy drawing element to
  191. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  192. func (f *File) addSheetLegacyDrawing(sheet string, rID int) {
  193. xlsx, _ := f.workSheetReader(sheet)
  194. xlsx.LegacyDrawing = &xlsxLegacyDrawing{
  195. RID: "rId" + strconv.Itoa(rID),
  196. }
  197. }
  198. // addSheetDrawing provides a function to add drawing element to
  199. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  200. func (f *File) addSheetDrawing(sheet string, rID int) {
  201. xlsx, _ := f.workSheetReader(sheet)
  202. xlsx.Drawing = &xlsxDrawing{
  203. RID: "rId" + strconv.Itoa(rID),
  204. }
  205. }
  206. // addSheetPicture provides a function to add picture element to
  207. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  208. func (f *File) addSheetPicture(sheet string, rID int) {
  209. xlsx, _ := f.workSheetReader(sheet)
  210. xlsx.Picture = &xlsxPicture{
  211. RID: "rId" + strconv.Itoa(rID),
  212. }
  213. }
  214. // countDrawings provides a function to get drawing files count storage in the
  215. // folder xl/drawings.
  216. func (f *File) countDrawings() int {
  217. c1, c2 := 0, 0
  218. for k := range f.XLSX {
  219. if strings.Contains(k, "xl/drawings/drawing") {
  220. c1++
  221. }
  222. }
  223. for rel := range f.Drawings {
  224. if strings.Contains(rel, "xl/drawings/drawing") {
  225. c2++
  226. }
  227. }
  228. if c1 < c2 {
  229. return c2
  230. }
  231. return c1
  232. }
  233. // addDrawingPicture provides a function to add picture by given sheet,
  234. // drawingXML, cell, file name, width, height relationship index and format
  235. // sets.
  236. func (f *File) addDrawingPicture(sheet, drawingXML, cell, file string, width, height, rID, hyperlinkRID int, formatSet *formatPicture) error {
  237. col, row, err := CellNameToCoordinates(cell)
  238. if err != nil {
  239. return err
  240. }
  241. width = int(float64(width) * formatSet.XScale)
  242. height = int(float64(height) * formatSet.YScale)
  243. col--
  244. row--
  245. colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 :=
  246. f.positionObjectPixels(sheet, col, row, formatSet.OffsetX, formatSet.OffsetY, width, height)
  247. content, cNvPrID := f.drawingParser(drawingXML)
  248. twoCellAnchor := xdrCellAnchor{}
  249. twoCellAnchor.EditAs = formatSet.Positioning
  250. from := xlsxFrom{}
  251. from.Col = colStart
  252. from.ColOff = formatSet.OffsetX * EMU
  253. from.Row = rowStart
  254. from.RowOff = formatSet.OffsetY * EMU
  255. to := xlsxTo{}
  256. to.Col = colEnd
  257. to.ColOff = x2 * EMU
  258. to.Row = rowEnd
  259. to.RowOff = y2 * EMU
  260. twoCellAnchor.From = &from
  261. twoCellAnchor.To = &to
  262. pic := xlsxPic{}
  263. pic.NvPicPr.CNvPicPr.PicLocks.NoChangeAspect = formatSet.NoChangeAspect
  264. pic.NvPicPr.CNvPr.ID = cNvPrID
  265. pic.NvPicPr.CNvPr.Descr = file
  266. pic.NvPicPr.CNvPr.Name = "Picture " + strconv.Itoa(cNvPrID)
  267. if hyperlinkRID != 0 {
  268. pic.NvPicPr.CNvPr.HlinkClick = &xlsxHlinkClick{
  269. R: SourceRelationship,
  270. RID: "rId" + strconv.Itoa(hyperlinkRID),
  271. }
  272. }
  273. pic.BlipFill.Blip.R = SourceRelationship
  274. pic.BlipFill.Blip.Embed = "rId" + strconv.Itoa(rID)
  275. pic.SpPr.PrstGeom.Prst = "rect"
  276. twoCellAnchor.Pic = &pic
  277. twoCellAnchor.ClientData = &xdrClientData{
  278. FLocksWithSheet: formatSet.FLocksWithSheet,
  279. FPrintsWithSheet: formatSet.FPrintsWithSheet,
  280. }
  281. content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
  282. f.Drawings[drawingXML] = content
  283. return err
  284. }
  285. // countMedia provides a function to get media files count storage in the
  286. // folder xl/media/image.
  287. func (f *File) countMedia() int {
  288. count := 0
  289. for k := range f.XLSX {
  290. if strings.Contains(k, "xl/media/image") {
  291. count++
  292. }
  293. }
  294. return count
  295. }
  296. // addMedia provides a function to add a picture into folder xl/media/image by
  297. // given file and extension name. Duplicate images are only actually stored once
  298. // and drawings that use it will reference the same image.
  299. func (f *File) addMedia(file []byte, ext string) string {
  300. count := f.countMedia()
  301. for name, existing := range f.XLSX {
  302. if !strings.HasPrefix(name, "xl/media/image") {
  303. continue
  304. }
  305. if bytes.Equal(file, existing) {
  306. return name
  307. }
  308. }
  309. media := "xl/media/image" + strconv.Itoa(count+1) + ext
  310. f.XLSX[media] = file
  311. return media
  312. }
  313. // setContentTypePartImageExtensions provides a function to set the content
  314. // type for relationship parts and the Main Document part.
  315. func (f *File) setContentTypePartImageExtensions() {
  316. var imageTypes = map[string]bool{"jpeg": false, "png": false, "gif": false, "tiff": false}
  317. content := f.contentTypesReader()
  318. for _, v := range content.Defaults {
  319. _, ok := imageTypes[v.Extension]
  320. if ok {
  321. imageTypes[v.Extension] = true
  322. }
  323. }
  324. for k, v := range imageTypes {
  325. if !v {
  326. content.Defaults = append(content.Defaults, xlsxDefault{
  327. Extension: k,
  328. ContentType: "image/" + k,
  329. })
  330. }
  331. }
  332. }
  333. // setContentTypePartVMLExtensions provides a function to set the content type
  334. // for relationship parts and the Main Document part.
  335. func (f *File) setContentTypePartVMLExtensions() {
  336. vml := false
  337. content := f.contentTypesReader()
  338. for _, v := range content.Defaults {
  339. if v.Extension == "vml" {
  340. vml = true
  341. }
  342. }
  343. if !vml {
  344. content.Defaults = append(content.Defaults, xlsxDefault{
  345. Extension: "vml",
  346. ContentType: "application/vnd.openxmlformats-officedocument.vmlDrawing",
  347. })
  348. }
  349. }
  350. // addContentTypePart provides a function to add content type part
  351. // relationships in the file [Content_Types].xml by given index.
  352. func (f *File) addContentTypePart(index int, contentType string) {
  353. setContentType := map[string]func(){
  354. "comments": f.setContentTypePartVMLExtensions,
  355. "drawings": f.setContentTypePartImageExtensions,
  356. }
  357. partNames := map[string]string{
  358. "chart": "/xl/charts/chart" + strconv.Itoa(index) + ".xml",
  359. "comments": "/xl/comments" + strconv.Itoa(index) + ".xml",
  360. "drawings": "/xl/drawings/drawing" + strconv.Itoa(index) + ".xml",
  361. "table": "/xl/tables/table" + strconv.Itoa(index) + ".xml",
  362. "pivotTable": "/xl/pivotTables/pivotTable" + strconv.Itoa(index) + ".xml",
  363. "pivotCache": "/xl/pivotCache/pivotCacheDefinition" + strconv.Itoa(index) + ".xml",
  364. }
  365. contentTypes := map[string]string{
  366. "chart": "application/vnd.openxmlformats-officedocument.drawingml.chart+xml",
  367. "comments": "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
  368. "drawings": "application/vnd.openxmlformats-officedocument.drawing+xml",
  369. "table": "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",
  370. "pivotTable": "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml",
  371. "pivotCache": "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml",
  372. }
  373. s, ok := setContentType[contentType]
  374. if ok {
  375. s()
  376. }
  377. content := f.contentTypesReader()
  378. for _, v := range content.Overrides {
  379. if v.PartName == partNames[contentType] {
  380. return
  381. }
  382. }
  383. content.Overrides = append(content.Overrides, xlsxOverride{
  384. PartName: partNames[contentType],
  385. ContentType: contentTypes[contentType],
  386. })
  387. }
  388. // getSheetRelationshipsTargetByID provides a function to get Target attribute
  389. // value in xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
  390. // relationship index.
  391. func (f *File) getSheetRelationshipsTargetByID(sheet, rID string) string {
  392. name, ok := f.sheetMap[trimSheetName(sheet)]
  393. if !ok {
  394. name = strings.ToLower(sheet) + ".xml"
  395. }
  396. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  397. sheetRels := f.relsReader(rels)
  398. if sheetRels == nil {
  399. sheetRels = &xlsxRelationships{}
  400. }
  401. for _, v := range sheetRels.Relationships {
  402. if v.ID == rID {
  403. return v.Target
  404. }
  405. }
  406. return ""
  407. }
  408. // GetPicture provides a function to get picture base name and raw content
  409. // embed in XLSX by given worksheet and cell name. This function returns the
  410. // file name in XLSX and file contents as []byte data types. For example:
  411. //
  412. // f, err := excelize.OpenFile("./Book1.xlsx")
  413. // if err != nil {
  414. // fmt.Println(err)
  415. // return
  416. // }
  417. // file, raw, err := f.GetPicture("Sheet1", "A2")
  418. // if err != nil {
  419. // fmt.Println(err)
  420. // return
  421. // }
  422. // err = ioutil.WriteFile(file, raw, 0644)
  423. // if err != nil {
  424. // fmt.Println(err)
  425. // }
  426. //
  427. func (f *File) GetPicture(sheet, cell string) (string, []byte, error) {
  428. col, row, err := CellNameToCoordinates(cell)
  429. if err != nil {
  430. return "", nil, err
  431. }
  432. col--
  433. row--
  434. xlsx, err := f.workSheetReader(sheet)
  435. if err != nil {
  436. return "", nil, err
  437. }
  438. if xlsx.Drawing == nil {
  439. return "", nil, err
  440. }
  441. target := f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
  442. drawingXML := strings.Replace(target, "..", "xl", -1)
  443. _, ok := f.XLSX[drawingXML]
  444. if !ok {
  445. return "", nil, err
  446. }
  447. drawingRelationships := strings.Replace(
  448. strings.Replace(target, "../drawings", "xl/drawings/_rels", -1), ".xml", ".xml.rels", -1)
  449. return f.getPicture(row, col, drawingXML, drawingRelationships)
  450. }
  451. // getPicture provides a function to get picture base name and raw content
  452. // embed in XLSX by given coordinates and drawing relationships.
  453. func (f *File) getPicture(row, col int, drawingXML, drawingRelationships string) (string, []byte, error) {
  454. wsDr, _ := f.drawingParser(drawingXML)
  455. for _, anchor := range wsDr.TwoCellAnchor {
  456. if anchor.From != nil && anchor.Pic != nil {
  457. if anchor.From.Col == col && anchor.From.Row == row {
  458. xlsxRelationship := f.getDrawingRelationships(drawingRelationships,
  459. anchor.Pic.BlipFill.Blip.Embed)
  460. _, ok := supportImageTypes[filepath.Ext(xlsxRelationship.Target)]
  461. if ok {
  462. return filepath.Base(xlsxRelationship.Target),
  463. []byte(f.XLSX[strings.Replace(xlsxRelationship.Target,
  464. "..", "xl", -1)]), nil
  465. }
  466. }
  467. }
  468. }
  469. decodeWsDr := decodeWsDr{}
  470. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(drawingXML)), &decodeWsDr)
  471. for _, anchor := range decodeWsDr.TwoCellAnchor {
  472. decodeTwoCellAnchor := decodeTwoCellAnchor{}
  473. _ = xml.Unmarshal([]byte("<decodeTwoCellAnchor>"+anchor.Content+"</decodeTwoCellAnchor>"), &decodeTwoCellAnchor)
  474. if decodeTwoCellAnchor.From != nil && decodeTwoCellAnchor.Pic != nil {
  475. if decodeTwoCellAnchor.From.Col == col && decodeTwoCellAnchor.From.Row == row {
  476. xlsxRelationship := f.getDrawingRelationships(drawingRelationships, decodeTwoCellAnchor.Pic.BlipFill.Blip.Embed)
  477. _, ok := supportImageTypes[filepath.Ext(xlsxRelationship.Target)]
  478. if ok {
  479. return filepath.Base(xlsxRelationship.Target), []byte(f.XLSX[strings.Replace(xlsxRelationship.Target, "..", "xl", -1)]), nil
  480. }
  481. }
  482. }
  483. }
  484. return "", nil, nil
  485. }
  486. // getDrawingRelationships provides a function to get drawing relationships
  487. // from xl/drawings/_rels/drawing%s.xml.rels by given file name and
  488. // relationship ID.
  489. func (f *File) getDrawingRelationships(rels, rID string) *xlsxRelationship {
  490. if drawingRels := f.relsReader(rels); drawingRels != nil {
  491. for _, v := range drawingRels.Relationships {
  492. if v.ID == rID {
  493. return &v
  494. }
  495. }
  496. }
  497. return nil
  498. }
  499. // drawingsWriter provides a function to save xl/drawings/drawing%d.xml after
  500. // serialize structure.
  501. func (f *File) drawingsWriter() {
  502. for path, d := range f.Drawings {
  503. if d != nil {
  504. v, _ := xml.Marshal(d)
  505. f.saveFileList(path, v)
  506. }
  507. }
  508. }