picture.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. // Package excelize providing a set of functions that allow you to write to
  2. // and read from XLSX files. Support reads and writes XLSX file generated by
  3. // Microsoft Excel™ 2007 and later. Support save file without losing original
  4. // charts of XLSX. This library needs Go version 1.8 or later.
  5. //
  6. // Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
  7. // this source code is governed by a BSD-style license that can be found in
  8. // the LICENSE file.
  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. var drawingHyperlinkRID int
  87. var hyperlinkType string
  88. // Check picture exists first.
  89. if _, err = os.Stat(picture); os.IsNotExist(err) {
  90. return err
  91. }
  92. ext, ok := supportImageTypes[path.Ext(picture)]
  93. if !ok {
  94. return errors.New("unsupported image extension")
  95. }
  96. readFile, err := os.Open(picture)
  97. if err != nil {
  98. return err
  99. }
  100. defer readFile.Close()
  101. image, _, _ := image.DecodeConfig(readFile)
  102. _, file := filepath.Split(picture)
  103. formatSet, err := parseFormatPictureSet(format)
  104. if err != nil {
  105. return err
  106. }
  107. // Read sheet data.
  108. xlsx := f.workSheetReader(sheet)
  109. // Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
  110. drawingID := f.countDrawings() + 1
  111. pictureID := f.countMedia() + 1
  112. drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  113. drawingID, drawingXML = f.prepareDrawing(xlsx, drawingID, sheet, drawingXML)
  114. drawingRID := f.addDrawingRelationships(drawingID, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, hyperlinkType)
  115. // Add picture with hyperlink.
  116. if formatSet.Hyperlink != "" && formatSet.HyperlinkType != "" {
  117. if formatSet.HyperlinkType == "External" {
  118. hyperlinkType = formatSet.HyperlinkType
  119. }
  120. drawingHyperlinkRID = f.addDrawingRelationships(drawingID, SourceRelationshipHyperLink, formatSet.Hyperlink, hyperlinkType)
  121. }
  122. f.addDrawingPicture(sheet, drawingXML, cell, file, image.Width, image.Height, drawingRID, drawingHyperlinkRID, formatSet)
  123. f.addMedia(picture, ext)
  124. f.addContentTypePart(drawingID, "drawings")
  125. return err
  126. }
  127. // addSheetRelationships provides a function to add
  128. // xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name, relationship
  129. // type and target.
  130. func (f *File) addSheetRelationships(sheet, relType, target, targetMode string) int {
  131. name, ok := f.sheetMap[trimSheetName(sheet)]
  132. if !ok {
  133. name = strings.ToLower(sheet) + ".xml"
  134. }
  135. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  136. var sheetRels xlsxWorkbookRels
  137. var rID = 1
  138. var ID bytes.Buffer
  139. ID.WriteString("rId")
  140. ID.WriteString(strconv.Itoa(rID))
  141. _, ok = f.XLSX[rels]
  142. if ok {
  143. ID.Reset()
  144. _ = xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  145. rID = len(sheetRels.Relationships) + 1
  146. ID.WriteString("rId")
  147. ID.WriteString(strconv.Itoa(rID))
  148. }
  149. sheetRels.Relationships = append(sheetRels.Relationships, xlsxWorkbookRelation{
  150. ID: ID.String(),
  151. Type: relType,
  152. Target: target,
  153. TargetMode: targetMode,
  154. })
  155. output, _ := xml.Marshal(sheetRels)
  156. f.saveFileList(rels, output)
  157. return rID
  158. }
  159. // deleteSheetRelationships provides a function to delete relationships in
  160. // xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
  161. // relationship index.
  162. func (f *File) deleteSheetRelationships(sheet, rID string) {
  163. name, ok := f.sheetMap[trimSheetName(sheet)]
  164. if !ok {
  165. name = strings.ToLower(sheet) + ".xml"
  166. }
  167. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  168. var sheetRels xlsxWorkbookRels
  169. _ = xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  170. for k, v := range sheetRels.Relationships {
  171. if v.ID == rID {
  172. sheetRels.Relationships = append(sheetRels.Relationships[:k], sheetRels.Relationships[k+1:]...)
  173. }
  174. }
  175. output, _ := xml.Marshal(sheetRels)
  176. f.saveFileList(rels, output)
  177. }
  178. // addSheetLegacyDrawing provides a function to add legacy drawing element to
  179. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  180. func (f *File) addSheetLegacyDrawing(sheet string, rID int) {
  181. xlsx := f.workSheetReader(sheet)
  182. xlsx.LegacyDrawing = &xlsxLegacyDrawing{
  183. RID: "rId" + strconv.Itoa(rID),
  184. }
  185. }
  186. // addSheetDrawing provides a function to add drawing element to
  187. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  188. func (f *File) addSheetDrawing(sheet string, rID int) {
  189. xlsx := f.workSheetReader(sheet)
  190. xlsx.Drawing = &xlsxDrawing{
  191. RID: "rId" + strconv.Itoa(rID),
  192. }
  193. }
  194. // addSheetPicture provides a function to add picture element to
  195. // xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
  196. func (f *File) addSheetPicture(sheet string, rID int) {
  197. xlsx := f.workSheetReader(sheet)
  198. xlsx.Picture = &xlsxPicture{
  199. RID: "rId" + strconv.Itoa(rID),
  200. }
  201. }
  202. // countDrawings provides a function to get drawing files count storage in the
  203. // folder xl/drawings.
  204. func (f *File) countDrawings() int {
  205. count := 0
  206. for k := range f.XLSX {
  207. if strings.Contains(k, "xl/drawings/drawing") {
  208. count++
  209. }
  210. }
  211. return count
  212. }
  213. // addDrawingPicture provides a function to add picture by given sheet,
  214. // drawingXML, cell, file name, width, height relationship index and format
  215. // sets.
  216. func (f *File) addDrawingPicture(sheet, drawingXML, cell, file string, width, height, rID, hyperlinkRID int, formatSet *formatPicture) {
  217. cell = strings.ToUpper(cell)
  218. fromCol := string(strings.Map(letterOnlyMapF, cell))
  219. fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  220. row := fromRow - 1
  221. col := TitleToNumber(fromCol)
  222. width = int(float64(width) * formatSet.XScale)
  223. height = int(float64(height) * formatSet.YScale)
  224. colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 := f.positionObjectPixels(sheet, col, row, formatSet.OffsetX, formatSet.OffsetY, width, height)
  225. content := xlsxWsDr{}
  226. content.A = NameSpaceDrawingML
  227. content.Xdr = NameSpaceDrawingMLSpreadSheet
  228. cNvPrID := f.drawingParser(drawingXML, &content)
  229. twoCellAnchor := xdrCellAnchor{}
  230. twoCellAnchor.EditAs = formatSet.Positioning
  231. from := xlsxFrom{}
  232. from.Col = colStart
  233. from.ColOff = formatSet.OffsetX * EMU
  234. from.Row = rowStart
  235. from.RowOff = formatSet.OffsetY * EMU
  236. to := xlsxTo{}
  237. to.Col = colEnd
  238. to.ColOff = x2 * EMU
  239. to.Row = rowEnd
  240. to.RowOff = y2 * EMU
  241. twoCellAnchor.From = &from
  242. twoCellAnchor.To = &to
  243. pic := xlsxPic{}
  244. pic.NvPicPr.CNvPicPr.PicLocks.NoChangeAspect = formatSet.NoChangeAspect
  245. pic.NvPicPr.CNvPr.ID = f.countCharts() + f.countMedia() + 1
  246. pic.NvPicPr.CNvPr.Descr = file
  247. pic.NvPicPr.CNvPr.Name = "Picture " + strconv.Itoa(cNvPrID)
  248. if hyperlinkRID != 0 {
  249. pic.NvPicPr.CNvPr.HlinkClick = &xlsxHlinkClick{
  250. R: SourceRelationship,
  251. RID: "rId" + strconv.Itoa(hyperlinkRID),
  252. }
  253. }
  254. pic.BlipFill.Blip.R = SourceRelationship
  255. pic.BlipFill.Blip.Embed = "rId" + strconv.Itoa(rID)
  256. pic.SpPr.PrstGeom.Prst = "rect"
  257. twoCellAnchor.Pic = &pic
  258. twoCellAnchor.ClientData = &xdrClientData{
  259. FLocksWithSheet: formatSet.FLocksWithSheet,
  260. FPrintsWithSheet: formatSet.FPrintsWithSheet,
  261. }
  262. content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
  263. output, _ := xml.Marshal(content)
  264. f.saveFileList(drawingXML, output)
  265. }
  266. // addDrawingRelationships provides a function to add image part relationships
  267. // in the file xl/drawings/_rels/drawing%d.xml.rels by given drawing index,
  268. // relationship type and target.
  269. func (f *File) addDrawingRelationships(index int, relType, target, targetMode string) int {
  270. var rels = "xl/drawings/_rels/drawing" + strconv.Itoa(index) + ".xml.rels"
  271. var drawingRels xlsxWorkbookRels
  272. var rID = 1
  273. var ID bytes.Buffer
  274. ID.WriteString("rId")
  275. ID.WriteString(strconv.Itoa(rID))
  276. _, ok := f.XLSX[rels]
  277. if ok {
  278. ID.Reset()
  279. _ = xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
  280. rID = len(drawingRels.Relationships) + 1
  281. ID.WriteString("rId")
  282. ID.WriteString(strconv.Itoa(rID))
  283. }
  284. drawingRels.Relationships = append(drawingRels.Relationships, xlsxWorkbookRelation{
  285. ID: ID.String(),
  286. Type: relType,
  287. Target: target,
  288. TargetMode: targetMode,
  289. })
  290. output, _ := xml.Marshal(drawingRels)
  291. f.saveFileList(rels, output)
  292. return rID
  293. }
  294. // countMedia provides a function to get media files count storage in the
  295. // folder xl/media/image.
  296. func (f *File) countMedia() int {
  297. count := 0
  298. for k := range f.XLSX {
  299. if strings.Contains(k, "xl/media/image") {
  300. count++
  301. }
  302. }
  303. return count
  304. }
  305. // addMedia provides a function to add picture into folder xl/media/image by
  306. // given file name and extension name.
  307. func (f *File) addMedia(file, ext string) {
  308. count := f.countMedia()
  309. dat, _ := ioutil.ReadFile(file)
  310. media := "xl/media/image" + strconv.Itoa(count+1) + ext
  311. f.XLSX[media] = dat
  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}
  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. }
  363. contentTypes := map[string]string{
  364. "chart": "application/vnd.openxmlformats-officedocument.drawingml.chart+xml",
  365. "comments": "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
  366. "drawings": "application/vnd.openxmlformats-officedocument.drawing+xml",
  367. "table": "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",
  368. }
  369. s, ok := setContentType[contentType]
  370. if ok {
  371. s()
  372. }
  373. content := f.contentTypesReader()
  374. for _, v := range content.Overrides {
  375. if v.PartName == partNames[contentType] {
  376. return
  377. }
  378. }
  379. content.Overrides = append(content.Overrides, xlsxOverride{
  380. PartName: partNames[contentType],
  381. ContentType: contentTypes[contentType],
  382. })
  383. }
  384. // getSheetRelationshipsTargetByID provides a function to get Target attribute
  385. // value in xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
  386. // relationship index.
  387. func (f *File) getSheetRelationshipsTargetByID(sheet, rID string) string {
  388. name, ok := f.sheetMap[trimSheetName(sheet)]
  389. if !ok {
  390. name = strings.ToLower(sheet) + ".xml"
  391. }
  392. var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
  393. var sheetRels xlsxWorkbookRels
  394. _ = xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  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. // xlsx, err := excelize.OpenFile("./Book1.xlsx")
  407. // if err != nil {
  408. // fmt.Println(err)
  409. // return
  410. // }
  411. // file, raw := xlsx.GetPicture("Sheet1", "A2")
  412. // if file == "" {
  413. // return
  414. // }
  415. // err := ioutil.WriteFile(file, raw, 0644)
  416. // if err != nil {
  417. // fmt.Println(err)
  418. // }
  419. //
  420. func (f *File) GetPicture(sheet, cell string) (string, []byte) {
  421. xlsx := f.workSheetReader(sheet)
  422. if xlsx.Drawing == nil {
  423. return "", []byte{}
  424. }
  425. target := f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
  426. drawingXML := strings.Replace(target, "..", "xl", -1)
  427. _, ok := f.XLSX[drawingXML]
  428. if !ok {
  429. return "", nil
  430. }
  431. decodeWsDr := decodeWsDr{}
  432. _ = xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
  433. cell = strings.ToUpper(cell)
  434. fromCol := string(strings.Map(letterOnlyMapF, cell))
  435. fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  436. row := fromRow - 1
  437. col := TitleToNumber(fromCol)
  438. drawingRelationships := strings.Replace(strings.Replace(target, "../drawings", "xl/drawings/_rels", -1), ".xml", ".xml.rels", -1)
  439. for _, anchor := range decodeWsDr.TwoCellAnchor {
  440. decodeTwoCellAnchor := decodeTwoCellAnchor{}
  441. _ = xml.Unmarshal([]byte("<decodeTwoCellAnchor>"+anchor.Content+"</decodeTwoCellAnchor>"), &decodeTwoCellAnchor)
  442. if decodeTwoCellAnchor.From != nil && decodeTwoCellAnchor.Pic != nil {
  443. if decodeTwoCellAnchor.From.Col == col && decodeTwoCellAnchor.From.Row == row {
  444. xlsxWorkbookRelation := f.getDrawingRelationships(drawingRelationships, decodeTwoCellAnchor.Pic.BlipFill.Blip.Embed)
  445. _, ok := supportImageTypes[filepath.Ext(xlsxWorkbookRelation.Target)]
  446. if ok {
  447. return filepath.Base(xlsxWorkbookRelation.Target), []byte(f.XLSX[strings.Replace(xlsxWorkbookRelation.Target, "..", "xl", -1)])
  448. }
  449. }
  450. }
  451. }
  452. return "", []byte{}
  453. }
  454. // getDrawingRelationships provides a function to get drawing relationships
  455. // from xl/drawings/_rels/drawing%s.xml.rels by given file name and
  456. // relationship ID.
  457. func (f *File) getDrawingRelationships(rels, rID string) *xlsxWorkbookRelation {
  458. _, ok := f.XLSX[rels]
  459. if !ok {
  460. return nil
  461. }
  462. var drawingRels xlsxWorkbookRels
  463. _ = xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
  464. for _, v := range drawingRels.Relationships {
  465. if v.ID == rID {
  466. return &v
  467. }
  468. }
  469. return nil
  470. }