picture.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. // Copyright 2016 - 2018 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.8 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. // xlsx := excelize.NewFile()
  55. // // Insert a picture.
  56. // err := xlsx.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 = xlsx.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 = xlsx.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 = xlsx.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. // xlsx := excelize.NewFile()
  114. //
  115. // file, err := ioutil.ReadFile("./image1.jpg")
  116. // if err != nil {
  117. // fmt.Println(err)
  118. // }
  119. // err = xlsx.AddPictureFromBytes("Sheet1", "A2", "", "Excel Logo", ".jpg", file)
  120. // if err != nil {
  121. // fmt.Println(err)
  122. // }
  123. // err = xlsx.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 err error
  131. var drawingHyperlinkRID int
  132. var hyperlinkType string
  133. ext, ok := supportImageTypes[extension]
  134. if !ok {
  135. return errors.New("unsupported image extension")
  136. }
  137. formatSet, err := parseFormatPictureSet(format)
  138. if err != nil {
  139. return err
  140. }
  141. image, _, err := image.DecodeConfig(bytes.NewReader(file))
  142. if err != nil {
  143. return err
  144. }
  145. // Read sheet data.
  146. xlsx := f.workSheetReader(sheet)
  147. // Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
  148. drawingID := f.countDrawings() + 1
  149. pictureID := f.countMedia() + 1
  150. drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  151. drawingID, drawingXML = f.prepareDrawing(xlsx, drawingID, sheet, drawingXML)
  152. drawingRID := f.addDrawingRelationships(drawingID, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, hyperlinkType)
  153. // Add picture with hyperlink.
  154. if formatSet.Hyperlink != "" && formatSet.HyperlinkType != "" {
  155. if formatSet.HyperlinkType == "External" {
  156. hyperlinkType = formatSet.HyperlinkType
  157. }
  158. drawingHyperlinkRID = f.addDrawingRelationships(drawingID, SourceRelationshipHyperLink, formatSet.Hyperlink, hyperlinkType)
  159. }
  160. f.addDrawingPicture(sheet, drawingXML, cell, name, image.Width, image.Height, drawingRID, drawingHyperlinkRID, formatSet)
  161. f.addMedia(file, ext)
  162. f.addContentTypePart(drawingID, "drawings")
  163. return err
  164. }
  165. // addSheetRelationships provides a function to add
  166. // xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name, relationship
  167. // type and target.
  168. func (f *File) addSheetRelationships(sheet, relType, target, targetMode string) int {
  169. name, ok := f.sheetMap[trimSheetName(sheet)]
  170. if !ok {
  171. name = strings.ToLower(sheet) + ".xml"
  172. }
  173. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  174. var sheetRels xlsxWorkbookRels
  175. var rID = 1
  176. var ID bytes.Buffer
  177. ID.WriteString("rId")
  178. ID.WriteString(strconv.Itoa(rID))
  179. _, ok = f.XLSX[rels]
  180. if ok {
  181. ID.Reset()
  182. _ = xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  183. rID = len(sheetRels.Relationships) + 1
  184. ID.WriteString("rId")
  185. ID.WriteString(strconv.Itoa(rID))
  186. }
  187. sheetRels.Relationships = append(sheetRels.Relationships, xlsxWorkbookRelation{
  188. ID: ID.String(),
  189. Type: relType,
  190. Target: target,
  191. TargetMode: targetMode,
  192. })
  193. output, _ := xml.Marshal(sheetRels)
  194. f.saveFileList(rels, output)
  195. return rID
  196. }
  197. // deleteSheetRelationships provides a function to delete relationships in
  198. // xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
  199. // relationship index.
  200. func (f *File) deleteSheetRelationships(sheet, rID string) {
  201. name, ok := f.sheetMap[trimSheetName(sheet)]
  202. if !ok {
  203. name = strings.ToLower(sheet) + ".xml"
  204. }
  205. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  206. var sheetRels xlsxWorkbookRels
  207. _ = xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  208. for k, v := range sheetRels.Relationships {
  209. if v.ID == rID {
  210. sheetRels.Relationships = append(sheetRels.Relationships[:k], sheetRels.Relationships[k+1:]...)
  211. }
  212. }
  213. output, _ := xml.Marshal(sheetRels)
  214. f.saveFileList(rels, output)
  215. }
  216. // addSheetLegacyDrawing provides a function to add legacy drawing element to
  217. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  218. func (f *File) addSheetLegacyDrawing(sheet string, rID int) {
  219. xlsx := f.workSheetReader(sheet)
  220. xlsx.LegacyDrawing = &xlsxLegacyDrawing{
  221. RID: "rId" + strconv.Itoa(rID),
  222. }
  223. }
  224. // addSheetDrawing provides a function to add drawing element to
  225. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  226. func (f *File) addSheetDrawing(sheet string, rID int) {
  227. xlsx := f.workSheetReader(sheet)
  228. xlsx.Drawing = &xlsxDrawing{
  229. RID: "rId" + strconv.Itoa(rID),
  230. }
  231. }
  232. // addSheetPicture provides a function to add picture element to
  233. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  234. func (f *File) addSheetPicture(sheet string, rID int) {
  235. xlsx := f.workSheetReader(sheet)
  236. xlsx.Picture = &xlsxPicture{
  237. RID: "rId" + strconv.Itoa(rID),
  238. }
  239. }
  240. // countDrawings provides a function to get drawing files count storage in the
  241. // folder xl/drawings.
  242. func (f *File) countDrawings() int {
  243. count := 0
  244. for k := range f.XLSX {
  245. if strings.Contains(k, "xl/drawings/drawing") {
  246. count++
  247. }
  248. }
  249. return count
  250. }
  251. // addDrawingPicture provides a function to add picture by given sheet,
  252. // drawingXML, cell, file name, width, height relationship index and format
  253. // sets.
  254. func (f *File) addDrawingPicture(sheet, drawingXML, cell, file string, width, height, rID, hyperlinkRID int, formatSet *formatPicture) {
  255. cell = strings.ToUpper(cell)
  256. fromCol := string(strings.Map(letterOnlyMapF, cell))
  257. fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  258. row := fromRow - 1
  259. col := TitleToNumber(fromCol)
  260. width = int(float64(width) * formatSet.XScale)
  261. height = int(float64(height) * formatSet.YScale)
  262. colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 := f.positionObjectPixels(sheet, col, row, formatSet.OffsetX, formatSet.OffsetY, width, height)
  263. content := xlsxWsDr{}
  264. content.A = NameSpaceDrawingML
  265. content.Xdr = NameSpaceDrawingMLSpreadSheet
  266. cNvPrID := f.drawingParser(drawingXML, &content)
  267. twoCellAnchor := xdrCellAnchor{}
  268. twoCellAnchor.EditAs = formatSet.Positioning
  269. from := xlsxFrom{}
  270. from.Col = colStart
  271. from.ColOff = formatSet.OffsetX * EMU
  272. from.Row = rowStart
  273. from.RowOff = formatSet.OffsetY * EMU
  274. to := xlsxTo{}
  275. to.Col = colEnd
  276. to.ColOff = x2 * EMU
  277. to.Row = rowEnd
  278. to.RowOff = y2 * EMU
  279. twoCellAnchor.From = &from
  280. twoCellAnchor.To = &to
  281. pic := xlsxPic{}
  282. pic.NvPicPr.CNvPicPr.PicLocks.NoChangeAspect = formatSet.NoChangeAspect
  283. pic.NvPicPr.CNvPr.ID = f.countCharts() + f.countMedia() + 1
  284. pic.NvPicPr.CNvPr.Descr = file
  285. pic.NvPicPr.CNvPr.Name = "Picture " + strconv.Itoa(cNvPrID)
  286. if hyperlinkRID != 0 {
  287. pic.NvPicPr.CNvPr.HlinkClick = &xlsxHlinkClick{
  288. R: SourceRelationship,
  289. RID: "rId" + strconv.Itoa(hyperlinkRID),
  290. }
  291. }
  292. pic.BlipFill.Blip.R = SourceRelationship
  293. pic.BlipFill.Blip.Embed = "rId" + strconv.Itoa(rID)
  294. pic.SpPr.PrstGeom.Prst = "rect"
  295. twoCellAnchor.Pic = &pic
  296. twoCellAnchor.ClientData = &xdrClientData{
  297. FLocksWithSheet: formatSet.FLocksWithSheet,
  298. FPrintsWithSheet: formatSet.FPrintsWithSheet,
  299. }
  300. content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
  301. output, _ := xml.Marshal(content)
  302. f.saveFileList(drawingXML, output)
  303. }
  304. // addDrawingRelationships provides a function to add image part relationships
  305. // in the file xl/drawings/_rels/drawing%d.xml.rels by given drawing index,
  306. // relationship type and target.
  307. func (f *File) addDrawingRelationships(index int, relType, target, targetMode string) int {
  308. var rels = "xl/drawings/_rels/drawing" + strconv.Itoa(index) + ".xml.rels"
  309. var drawingRels xlsxWorkbookRels
  310. var rID = 1
  311. var ID bytes.Buffer
  312. ID.WriteString("rId")
  313. ID.WriteString(strconv.Itoa(rID))
  314. _, ok := f.XLSX[rels]
  315. if ok {
  316. ID.Reset()
  317. _ = xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
  318. rID = len(drawingRels.Relationships) + 1
  319. ID.WriteString("rId")
  320. ID.WriteString(strconv.Itoa(rID))
  321. }
  322. drawingRels.Relationships = append(drawingRels.Relationships, xlsxWorkbookRelation{
  323. ID: ID.String(),
  324. Type: relType,
  325. Target: target,
  326. TargetMode: targetMode,
  327. })
  328. output, _ := xml.Marshal(drawingRels)
  329. f.saveFileList(rels, output)
  330. return rID
  331. }
  332. // countMedia provides a function to get media files count storage in the
  333. // folder xl/media/image.
  334. func (f *File) countMedia() int {
  335. count := 0
  336. for k := range f.XLSX {
  337. if strings.Contains(k, "xl/media/image") {
  338. count++
  339. }
  340. }
  341. return count
  342. }
  343. // addMedia provides a function to add picture into folder xl/media/image by
  344. // given file and extension name.
  345. func (f *File) addMedia(file []byte, ext string) {
  346. count := f.countMedia()
  347. media := "xl/media/image" + strconv.Itoa(count+1) + ext
  348. f.XLSX[media] = file
  349. }
  350. // setContentTypePartImageExtensions provides a function to set the content
  351. // type for relationship parts and the Main Document part.
  352. func (f *File) setContentTypePartImageExtensions() {
  353. var imageTypes = map[string]bool{"jpeg": false, "png": false, "gif": false}
  354. content := f.contentTypesReader()
  355. for _, v := range content.Defaults {
  356. _, ok := imageTypes[v.Extension]
  357. if ok {
  358. imageTypes[v.Extension] = true
  359. }
  360. }
  361. for k, v := range imageTypes {
  362. if !v {
  363. content.Defaults = append(content.Defaults, xlsxDefault{
  364. Extension: k,
  365. ContentType: "image/" + k,
  366. })
  367. }
  368. }
  369. }
  370. // setContentTypePartVMLExtensions provides a function to set the content type
  371. // for relationship parts and the Main Document part.
  372. func (f *File) setContentTypePartVMLExtensions() {
  373. vml := false
  374. content := f.contentTypesReader()
  375. for _, v := range content.Defaults {
  376. if v.Extension == "vml" {
  377. vml = true
  378. }
  379. }
  380. if !vml {
  381. content.Defaults = append(content.Defaults, xlsxDefault{
  382. Extension: "vml",
  383. ContentType: "application/vnd.openxmlformats-officedocument.vmlDrawing",
  384. })
  385. }
  386. }
  387. // addContentTypePart provides a function to add content type part
  388. // relationships in the file [Content_Types].xml by given index.
  389. func (f *File) addContentTypePart(index int, contentType string) {
  390. setContentType := map[string]func(){
  391. "comments": f.setContentTypePartVMLExtensions,
  392. "drawings": f.setContentTypePartImageExtensions,
  393. }
  394. partNames := map[string]string{
  395. "chart": "/xl/charts/chart" + strconv.Itoa(index) + ".xml",
  396. "comments": "/xl/comments" + strconv.Itoa(index) + ".xml",
  397. "drawings": "/xl/drawings/drawing" + strconv.Itoa(index) + ".xml",
  398. "table": "/xl/tables/table" + strconv.Itoa(index) + ".xml",
  399. }
  400. contentTypes := map[string]string{
  401. "chart": "application/vnd.openxmlformats-officedocument.drawingml.chart+xml",
  402. "comments": "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
  403. "drawings": "application/vnd.openxmlformats-officedocument.drawing+xml",
  404. "table": "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",
  405. }
  406. s, ok := setContentType[contentType]
  407. if ok {
  408. s()
  409. }
  410. content := f.contentTypesReader()
  411. for _, v := range content.Overrides {
  412. if v.PartName == partNames[contentType] {
  413. return
  414. }
  415. }
  416. content.Overrides = append(content.Overrides, xlsxOverride{
  417. PartName: partNames[contentType],
  418. ContentType: contentTypes[contentType],
  419. })
  420. }
  421. // getSheetRelationshipsTargetByID provides a function to get Target attribute
  422. // value in xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
  423. // relationship index.
  424. func (f *File) getSheetRelationshipsTargetByID(sheet, rID string) string {
  425. name, ok := f.sheetMap[trimSheetName(sheet)]
  426. if !ok {
  427. name = strings.ToLower(sheet) + ".xml"
  428. }
  429. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  430. var sheetRels xlsxWorkbookRels
  431. _ = xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  432. for _, v := range sheetRels.Relationships {
  433. if v.ID == rID {
  434. return v.Target
  435. }
  436. }
  437. return ""
  438. }
  439. // GetPicture provides a function to get picture base name and raw content
  440. // embed in XLSX by given worksheet and cell name. This function returns the
  441. // file name in XLSX and file contents as []byte data types. For example:
  442. //
  443. // xlsx, err := excelize.OpenFile("./Book1.xlsx")
  444. // if err != nil {
  445. // fmt.Println(err)
  446. // return
  447. // }
  448. // file, raw := xlsx.GetPicture("Sheet1", "A2")
  449. // if file == "" {
  450. // return
  451. // }
  452. // err := ioutil.WriteFile(file, raw, 0644)
  453. // if err != nil {
  454. // fmt.Println(err)
  455. // }
  456. //
  457. func (f *File) GetPicture(sheet, cell string) (string, []byte) {
  458. xlsx := f.workSheetReader(sheet)
  459. if xlsx.Drawing == nil {
  460. return "", []byte{}
  461. }
  462. target := f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
  463. drawingXML := strings.Replace(target, "..", "xl", -1)
  464. _, ok := f.XLSX[drawingXML]
  465. if !ok {
  466. return "", nil
  467. }
  468. decodeWsDr := decodeWsDr{}
  469. _ = xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
  470. cell = strings.ToUpper(cell)
  471. fromCol := string(strings.Map(letterOnlyMapF, cell))
  472. fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  473. row := fromRow - 1
  474. col := TitleToNumber(fromCol)
  475. drawingRelationships := strings.Replace(strings.Replace(target, "../drawings", "xl/drawings/_rels", -1), ".xml", ".xml.rels", -1)
  476. for _, anchor := range decodeWsDr.TwoCellAnchor {
  477. decodeTwoCellAnchor := decodeTwoCellAnchor{}
  478. _ = xml.Unmarshal([]byte("<decodeTwoCellAnchor>"+anchor.Content+"</decodeTwoCellAnchor>"), &decodeTwoCellAnchor)
  479. if decodeTwoCellAnchor.From != nil && decodeTwoCellAnchor.Pic != nil {
  480. if decodeTwoCellAnchor.From.Col == col && decodeTwoCellAnchor.From.Row == row {
  481. xlsxWorkbookRelation := f.getDrawingRelationships(drawingRelationships, decodeTwoCellAnchor.Pic.BlipFill.Blip.Embed)
  482. _, ok := supportImageTypes[filepath.Ext(xlsxWorkbookRelation.Target)]
  483. if ok {
  484. return filepath.Base(xlsxWorkbookRelation.Target), []byte(f.XLSX[strings.Replace(xlsxWorkbookRelation.Target, "..", "xl", -1)])
  485. }
  486. }
  487. }
  488. }
  489. return "", []byte{}
  490. }
  491. // getDrawingRelationships provides a function to get drawing relationships
  492. // from xl/drawings/_rels/drawing%s.xml.rels by given file name and
  493. // relationship ID.
  494. func (f *File) getDrawingRelationships(rels, rID string) *xlsxWorkbookRelation {
  495. _, ok := f.XLSX[rels]
  496. if !ok {
  497. return nil
  498. }
  499. var drawingRels xlsxWorkbookRels
  500. _ = xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
  501. for _, v := range drawingRels.Relationships {
  502. if v.ID == rID {
  503. return &v
  504. }
  505. }
  506. return nil
  507. }