picture.go 18 KB

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