picture.go 16 KB

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