picture.go 14 KB

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