picture.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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 function to parse the format settings of the
  16. // picture with default value.
  17. func parseFormatPictureSet(formatSet string) *formatPicture {
  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. json.Unmarshal([]byte(formatSet), &format)
  28. return &format
  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. // "os"
  39. // _ "image/gif"
  40. // _ "image/jpeg"
  41. // _ "image/png"
  42. //
  43. // "github.com/Luxurioust/excelize"
  44. // )
  45. //
  46. // func main() {
  47. // xlsx := excelize.CreateFile()
  48. // // Insert a picture.
  49. // err := xlsx.AddPicture("Sheet1", "A2", "./image1.jpg", "")
  50. // if err != nil {
  51. // fmt.Println(err)
  52. // }
  53. // // Insert a picture to sheet with scaling.
  54. // err = xlsx.AddPicture("Sheet1", "D2", "./image1.png", `{"x_scale": 0.5, "y_scale": 0.5}`)
  55. // if err != nil {
  56. // fmt.Println(err)
  57. // }
  58. // // Insert a picture offset in the cell with printing support.
  59. // err = xlsx.AddPicture("Sheet1", "H2", "./image3.gif", `{"x_offset": 15, "y_offset": 10, "print_obj": true, "lock_aspect_ratio": false, "locked": false}`)
  60. // if err != nil {
  61. // fmt.Println(err)
  62. // }
  63. // err = xlsx.WriteTo("./Workbook.xlsx")
  64. // if err != nil {
  65. // fmt.Println(err)
  66. // os.Exit(1)
  67. // }
  68. // }
  69. //
  70. func (f *File) AddPicture(sheet, cell, picture, format string) error {
  71. var err error
  72. // Check picture exists first.
  73. if _, err = os.Stat(picture); os.IsNotExist(err) {
  74. return err
  75. }
  76. ext, ok := supportImageTypes[path.Ext(picture)]
  77. if !ok {
  78. return errors.New("Unsupported image extension")
  79. }
  80. readFile, _ := os.Open(picture)
  81. image, _, err := image.DecodeConfig(readFile)
  82. _, file := filepath.Split(picture)
  83. formatSet := parseFormatPictureSet(format)
  84. // Read sheet data.
  85. xlsx := f.workSheetReader(sheet)
  86. // Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
  87. drawingID := f.countDrawings() + 1
  88. pictureID := f.countMedia() + 1
  89. drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  90. sheetRelationshipsDrawingXML := "../drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  91. var drawingRID int
  92. if xlsx.Drawing != nil {
  93. // The worksheet already has a picture or chart relationships, use the relationships drawing ../drawings/drawing%d.xml.
  94. sheetRelationshipsDrawingXML = f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
  95. drawingID, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(sheetRelationshipsDrawingXML, "../drawings/drawing"), ".xml"))
  96. drawingXML = strings.Replace(sheetRelationshipsDrawingXML, "..", "xl", -1)
  97. } else {
  98. // Add first picture for given sheet.
  99. rID := f.addSheetRelationships(sheet, SourceRelationshipDrawingML, sheetRelationshipsDrawingXML, "")
  100. f.addSheetDrawing(sheet, rID)
  101. }
  102. drawingRID = f.addDrawingRelationships(drawingID, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext)
  103. f.addDrawingPicture(sheet, drawingXML, cell, file, image.Width, image.Height, drawingRID, formatSet)
  104. f.addMedia(picture, ext)
  105. f.addDrawingContentTypePart(drawingID)
  106. return err
  107. }
  108. // addSheetRelationships provides function to add
  109. // xl/worksheets/_rels/sheet%d.xml.rels by given sheet name, relationship type
  110. // and target.
  111. func (f *File) addSheetRelationships(sheet, relType, target, targetMode string) int {
  112. var rels = "xl/worksheets/_rels/" + strings.ToLower(sheet) + ".xml.rels"
  113. var sheetRels xlsxWorkbookRels
  114. var rID = 1
  115. var ID bytes.Buffer
  116. ID.WriteString("rId")
  117. ID.WriteString(strconv.Itoa(rID))
  118. _, ok := f.XLSX[rels]
  119. if ok {
  120. ID.Reset()
  121. xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  122. rID = len(sheetRels.Relationships) + 1
  123. ID.WriteString("rId")
  124. ID.WriteString(strconv.Itoa(rID))
  125. }
  126. sheetRels.Relationships = append(sheetRels.Relationships, xlsxWorkbookRelation{
  127. ID: ID.String(),
  128. Type: relType,
  129. Target: target,
  130. TargetMode: targetMode,
  131. })
  132. output, _ := xml.Marshal(sheetRels)
  133. f.saveFileList(rels, string(output))
  134. return rID
  135. }
  136. // addSheetLegacyDrawing provides function to add legacy drawing element to
  137. // xl/worksheets/sheet%d.xml by given sheet name and relationship index.
  138. func (f *File) addSheetLegacyDrawing(sheet string, rID int) {
  139. xlsx := f.workSheetReader(sheet)
  140. xlsx.LegacyDrawing = &xlsxLegacyDrawing{
  141. RID: "rId" + strconv.Itoa(rID),
  142. }
  143. }
  144. // addSheetDrawing provides function to add drawing element to
  145. // xl/worksheets/sheet%d.xml by given sheet name and relationship index.
  146. func (f *File) addSheetDrawing(sheet string, rID int) {
  147. xlsx := f.workSheetReader(sheet)
  148. xlsx.Drawing = &xlsxDrawing{
  149. RID: "rId" + strconv.Itoa(rID),
  150. }
  151. }
  152. // addSheetPicture provides function to add picture element to
  153. // xl/worksheets/sheet%d.xml by given sheet name and relationship index.
  154. func (f *File) addSheetPicture(sheet string, rID int) {
  155. xlsx := f.workSheetReader(sheet)
  156. xlsx.Picture = &xlsxPicture{
  157. RID: "rId" + strconv.Itoa(rID),
  158. }
  159. }
  160. // countDrawings provides function to get drawing files count storage in the
  161. // folder xl/drawings.
  162. func (f *File) countDrawings() int {
  163. count := 0
  164. for k := range f.XLSX {
  165. if strings.Contains(k, "xl/drawings/drawing") {
  166. count++
  167. }
  168. }
  169. return count
  170. }
  171. // addDrawingPicture provides function to add picture by given sheet,
  172. // drawingXML, cell, file name, width, height relationship index and format
  173. // sets. In order to solve the problem that the label structure is changed after
  174. // serialization and deserialization, two different structures: decodeWsDr and
  175. // encodeWsDr are defined.
  176. func (f *File) addDrawingPicture(sheet, drawingXML, cell, file string, width, height, rID int, formatSet *formatPicture) {
  177. cell = strings.ToUpper(cell)
  178. fromCol := string(strings.Map(letterOnlyMapF, cell))
  179. fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  180. row := fromRow - 1
  181. col := titleToNumber(fromCol)
  182. width = int(float64(width) * formatSet.XScale)
  183. height = int(float64(height) * formatSet.YScale)
  184. colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 := f.positionObjectPixels(sheet, col, row, formatSet.OffsetX, formatSet.OffsetY, width, height)
  185. content := xlsxWsDr{}
  186. content.A = NameSpaceDrawingML
  187. content.Xdr = NameSpaceDrawingMLSpreadSheet
  188. cNvPrID := 1
  189. _, ok := f.XLSX[drawingXML]
  190. if ok { // Append Model
  191. decodeWsDr := decodeWsDr{}
  192. xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
  193. cNvPrID = len(decodeWsDr.OneCellAnchor) + len(decodeWsDr.TwoCellAnchor) + 1
  194. for _, v := range decodeWsDr.OneCellAnchor {
  195. content.OneCellAnchor = append(content.OneCellAnchor, &xdrCellAnchor{
  196. EditAs: v.EditAs,
  197. GraphicFrame: v.Content,
  198. })
  199. }
  200. for _, v := range decodeWsDr.TwoCellAnchor {
  201. content.TwoCellAnchor = append(content.TwoCellAnchor, &xdrCellAnchor{
  202. EditAs: v.EditAs,
  203. GraphicFrame: v.Content,
  204. })
  205. }
  206. }
  207. twoCellAnchor := xdrCellAnchor{}
  208. twoCellAnchor.EditAs = "oneCell"
  209. from := xlsxFrom{}
  210. from.Col = colStart
  211. from.ColOff = formatSet.OffsetX * EMU
  212. from.Row = rowStart
  213. from.RowOff = formatSet.OffsetY * EMU
  214. to := xlsxTo{}
  215. to.Col = colEnd
  216. to.ColOff = x2 * EMU
  217. to.Row = rowEnd
  218. to.RowOff = y2 * EMU
  219. twoCellAnchor.From = &from
  220. twoCellAnchor.To = &to
  221. pic := xlsxPic{}
  222. pic.NvPicPr.CNvPicPr.PicLocks.NoChangeAspect = formatSet.NoChangeAspect
  223. pic.NvPicPr.CNvPr.ID = f.countCharts() + f.countMedia() + 1
  224. pic.NvPicPr.CNvPr.Descr = file
  225. pic.NvPicPr.CNvPr.Name = "Picture " + strconv.Itoa(cNvPrID)
  226. pic.BlipFill.Blip.R = SourceRelationship
  227. pic.BlipFill.Blip.Embed = "rId" + strconv.Itoa(rID)
  228. pic.SpPr.PrstGeom.Prst = "rect"
  229. twoCellAnchor.Pic = &pic
  230. twoCellAnchor.ClientData = &xdrClientData{
  231. FLocksWithSheet: formatSet.FLocksWithSheet,
  232. FPrintsWithSheet: formatSet.FPrintsWithSheet,
  233. }
  234. content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
  235. output, _ := xml.Marshal(content)
  236. f.saveFileList(drawingXML, string(output))
  237. }
  238. // addDrawingRelationships provides function to add image part relationships in
  239. // the file xl/drawings/_rels/drawing%d.xml.rels by given drawing index,
  240. // relationship type and target.
  241. func (f *File) addDrawingRelationships(index int, relType string, target string) int {
  242. var rels = "xl/drawings/_rels/drawing" + strconv.Itoa(index) + ".xml.rels"
  243. var drawingRels xlsxWorkbookRels
  244. var rID = 1
  245. var ID bytes.Buffer
  246. ID.WriteString("rId")
  247. ID.WriteString(strconv.Itoa(rID))
  248. _, ok := f.XLSX[rels]
  249. if ok {
  250. ID.Reset()
  251. xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
  252. rID = len(drawingRels.Relationships) + 1
  253. ID.WriteString("rId")
  254. ID.WriteString(strconv.Itoa(rID))
  255. }
  256. drawingRels.Relationships = append(drawingRels.Relationships, xlsxWorkbookRelation{
  257. ID: ID.String(),
  258. Type: relType,
  259. Target: target,
  260. })
  261. output, _ := xml.Marshal(drawingRels)
  262. f.saveFileList(rels, string(output))
  263. return rID
  264. }
  265. // countMedia provides function to get media files count storage in the folder
  266. // xl/media/image.
  267. func (f *File) countMedia() int {
  268. count := 0
  269. for k := range f.XLSX {
  270. if strings.Contains(k, "xl/media/image") {
  271. count++
  272. }
  273. }
  274. return count
  275. }
  276. // addMedia provides function to add picture into folder xl/media/image by given
  277. // file name and extension name.
  278. func (f *File) addMedia(file string, ext string) {
  279. count := f.countMedia()
  280. dat, _ := ioutil.ReadFile(file)
  281. media := "xl/media/image" + strconv.Itoa(count+1) + ext
  282. f.XLSX[media] = string(dat)
  283. }
  284. // setContentTypePartImageExtensions provides function to set the content type
  285. // for relationship parts and the Main Document part.
  286. func (f *File) setContentTypePartImageExtensions() {
  287. var imageTypes = map[string]bool{"jpeg": false, "png": false, "gif": false}
  288. content := f.contentTypesReader()
  289. for _, v := range content.Defaults {
  290. _, ok := imageTypes[v.Extension]
  291. if ok {
  292. imageTypes[v.Extension] = true
  293. }
  294. }
  295. for k, v := range imageTypes {
  296. if !v {
  297. content.Defaults = append(content.Defaults, xlsxDefault{
  298. Extension: k,
  299. ContentType: "image/" + k,
  300. })
  301. }
  302. }
  303. }
  304. // setContentTypePartVMLExtensions provides function to set the content type
  305. // for relationship parts and the Main Document part.
  306. func (f *File) setContentTypePartVMLExtensions() {
  307. vml := false
  308. content := f.contentTypesReader()
  309. for _, v := range content.Defaults {
  310. if v.Extension == "vml" {
  311. vml = true
  312. }
  313. }
  314. if !vml {
  315. content.Defaults = append(content.Defaults, xlsxDefault{
  316. Extension: "vml",
  317. ContentType: "application/vnd.openxmlformats-officedocument.vmlDrawing",
  318. })
  319. }
  320. }
  321. // addDrawingContentTypePart provides function to add image part relationships
  322. // in the file [Content_Types].xml by given drawing index.
  323. func (f *File) addDrawingContentTypePart(index int) {
  324. f.setContentTypePartImageExtensions()
  325. content := f.contentTypesReader()
  326. for _, v := range content.Overrides {
  327. if v.PartName == "/xl/drawings/drawing"+strconv.Itoa(index)+".xml" {
  328. return
  329. }
  330. }
  331. content.Overrides = append(content.Overrides, xlsxOverride{
  332. PartName: "/xl/drawings/drawing" + strconv.Itoa(index) + ".xml",
  333. ContentType: "application/vnd.openxmlformats-officedocument.drawing+xml",
  334. })
  335. }
  336. // addCommentsContentTypePart provides function to add comments part
  337. // relationships in the file [Content_Types].xml by given comment index.
  338. func (f *File) addCommentsContentTypePart(index int) {
  339. f.setContentTypePartVMLExtensions()
  340. content := f.contentTypesReader()
  341. for _, v := range content.Overrides {
  342. if v.PartName == "/xl/comments"+strconv.Itoa(index)+".xml" {
  343. return
  344. }
  345. }
  346. content.Overrides = append(content.Overrides, xlsxOverride{
  347. PartName: "/xl/comments" + strconv.Itoa(index) + ".xml",
  348. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
  349. })
  350. }
  351. // getSheetRelationshipsTargetByID provides function to get Target attribute
  352. // value in xl/worksheets/_rels/sheet%d.xml.rels by given sheet name and
  353. // relationship index.
  354. func (f *File) getSheetRelationshipsTargetByID(sheet string, rID string) string {
  355. var rels = "xl/worksheets/_rels/" + strings.ToLower(sheet) + ".xml.rels"
  356. var sheetRels xlsxWorkbookRels
  357. xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  358. for _, v := range sheetRels.Relationships {
  359. if v.ID == rID {
  360. return v.Target
  361. }
  362. }
  363. return ""
  364. }
  365. // GetPicture provides function to get picture base name and raw content embed
  366. // in XLSX by given worksheet and cell name. This function returns the file name
  367. // in XLSX and file contents as []byte data types. For example:
  368. //
  369. // xlsx, err := excelize.OpenFile("./Workbook.xlsx")
  370. // if err != nil {
  371. // fmt.Println(err)
  372. // os.Exit(1)
  373. // }
  374. // file, raw := xlsx.GetPicture("Sheet1", "A2")
  375. // if file == "" {
  376. // os.Exit(1)
  377. // }
  378. // err := ioutil.WriteFile(file, raw, 0644)
  379. // if err != nil {
  380. // fmt.Println(err)
  381. // os.Exit(1)
  382. // }
  383. //
  384. func (f *File) GetPicture(sheet, cell string) (string, []byte) {
  385. xlsx := f.workSheetReader(sheet)
  386. if xlsx.Drawing == nil {
  387. return "", []byte{}
  388. }
  389. target := f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
  390. drawingXML := strings.Replace(target, "..", "xl", -1)
  391. _, ok := f.XLSX[drawingXML]
  392. if !ok {
  393. return "", []byte{}
  394. }
  395. decodeWsDr := decodeWsDr{}
  396. xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
  397. cell = strings.ToUpper(cell)
  398. fromCol := string(strings.Map(letterOnlyMapF, cell))
  399. fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  400. row := fromRow - 1
  401. col := titleToNumber(fromCol)
  402. drawingRelationships := strings.Replace(strings.Replace(target, "../drawings", "xl/drawings/_rels", -1), ".xml", ".xml.rels", -1)
  403. for _, anchor := range decodeWsDr.TwoCellAnchor {
  404. decodeTwoCellAnchor := decodeTwoCellAnchor{}
  405. xml.Unmarshal([]byte("<decodeTwoCellAnchor>"+anchor.Content+"</decodeTwoCellAnchor>"), &decodeTwoCellAnchor)
  406. if decodeTwoCellAnchor.From == nil || decodeTwoCellAnchor.Pic == nil {
  407. continue
  408. }
  409. if decodeTwoCellAnchor.From.Col == col && decodeTwoCellAnchor.From.Row == row {
  410. xlsxWorkbookRelation := f.getDrawingRelationships(drawingRelationships, decodeTwoCellAnchor.Pic.BlipFill.Blip.Embed)
  411. _, ok := supportImageTypes[filepath.Ext(xlsxWorkbookRelation.Target)]
  412. if !ok {
  413. continue
  414. }
  415. return filepath.Base(xlsxWorkbookRelation.Target), []byte(f.XLSX[strings.Replace(xlsxWorkbookRelation.Target, "..", "xl", -1)])
  416. }
  417. }
  418. return "", []byte{}
  419. }
  420. // getDrawingRelationships provides function to get drawing relationships from
  421. // xl/drawings/_rels/drawing%s.xml.rels by given file name and relationship ID.
  422. func (f *File) getDrawingRelationships(rels, rID string) *xlsxWorkbookRelation {
  423. _, ok := f.XLSX[rels]
  424. if !ok {
  425. return nil
  426. }
  427. var drawingRels xlsxWorkbookRels
  428. xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
  429. for _, v := range drawingRels.Relationships {
  430. if v.ID != rID {
  431. continue
  432. }
  433. return &v
  434. }
  435. return nil
  436. }