picture.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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/xuri/excelize"
  44. // )
  45. //
  46. // func main() {
  47. // xlsx := excelize.NewFile()
  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.SaveAs("./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. drawingID, drawingXML = f.prepareDrawing(xlsx, drawingID, sheet, drawingXML)
  91. drawingRID := f.addDrawingRelationships(drawingID, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext)
  92. f.addDrawingPicture(sheet, drawingXML, cell, file, image.Width, image.Height, drawingRID, formatSet)
  93. f.addMedia(picture, ext)
  94. f.addContentTypePart(drawingID, "drawings")
  95. return err
  96. }
  97. // addSheetRelationships provides function to add
  98. // xl/worksheets/_rels/sheet%d.xml.rels by given sheet name, relationship type
  99. // and target.
  100. func (f *File) addSheetRelationships(sheet, relType, target, targetMode string) int {
  101. var rels = "xl/worksheets/_rels/" + strings.ToLower(sheet) + ".xml.rels"
  102. var sheetRels xlsxWorkbookRels
  103. var rID = 1
  104. var ID bytes.Buffer
  105. ID.WriteString("rId")
  106. ID.WriteString(strconv.Itoa(rID))
  107. _, ok := f.XLSX[rels]
  108. if ok {
  109. ID.Reset()
  110. xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  111. rID = len(sheetRels.Relationships) + 1
  112. ID.WriteString("rId")
  113. ID.WriteString(strconv.Itoa(rID))
  114. }
  115. sheetRels.Relationships = append(sheetRels.Relationships, xlsxWorkbookRelation{
  116. ID: ID.String(),
  117. Type: relType,
  118. Target: target,
  119. TargetMode: targetMode,
  120. })
  121. output, _ := xml.Marshal(sheetRels)
  122. f.saveFileList(rels, string(output))
  123. return rID
  124. }
  125. // deleteSheetRelationships provides function to delete relationships in
  126. // xl/worksheets/_rels/sheet%d.xml.rels by given sheet name and relationship
  127. // index.
  128. func (f *File) deleteSheetRelationships(sheet, rID string) {
  129. var rels = "xl/worksheets/_rels/" + strings.ToLower(sheet) + ".xml.rels"
  130. var sheetRels xlsxWorkbookRels
  131. xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  132. for k, v := range sheetRels.Relationships {
  133. if v.ID != rID {
  134. continue
  135. }
  136. sheetRels.Relationships = append(sheetRels.Relationships[:k], sheetRels.Relationships[k+1:]...)
  137. }
  138. output, _ := xml.Marshal(sheetRels)
  139. f.saveFileList(rels, string(output))
  140. }
  141. // addSheetLegacyDrawing provides function to add legacy drawing element to
  142. // xl/worksheets/sheet%d.xml by given sheet name and relationship index.
  143. func (f *File) addSheetLegacyDrawing(sheet string, rID int) {
  144. xlsx := f.workSheetReader(sheet)
  145. xlsx.LegacyDrawing = &xlsxLegacyDrawing{
  146. RID: "rId" + strconv.Itoa(rID),
  147. }
  148. }
  149. // addSheetDrawing provides function to add drawing element to
  150. // xl/worksheets/sheet%d.xml by given sheet name and relationship index.
  151. func (f *File) addSheetDrawing(sheet string, rID int) {
  152. xlsx := f.workSheetReader(sheet)
  153. xlsx.Drawing = &xlsxDrawing{
  154. RID: "rId" + strconv.Itoa(rID),
  155. }
  156. }
  157. // addSheetPicture provides function to add picture element to
  158. // xl/worksheets/sheet%d.xml by given sheet name and relationship index.
  159. func (f *File) addSheetPicture(sheet string, rID int) {
  160. xlsx := f.workSheetReader(sheet)
  161. xlsx.Picture = &xlsxPicture{
  162. RID: "rId" + strconv.Itoa(rID),
  163. }
  164. }
  165. // countDrawings provides function to get drawing files count storage in the
  166. // folder xl/drawings.
  167. func (f *File) countDrawings() int {
  168. count := 0
  169. for k := range f.XLSX {
  170. if strings.Contains(k, "xl/drawings/drawing") {
  171. count++
  172. }
  173. }
  174. return count
  175. }
  176. // addDrawingPicture provides function to add picture by given sheet,
  177. // drawingXML, cell, file name, width, height relationship index and format
  178. // sets.
  179. func (f *File) addDrawingPicture(sheet, drawingXML, cell, file string, width, height, rID int, formatSet *formatPicture) {
  180. cell = strings.ToUpper(cell)
  181. fromCol := string(strings.Map(letterOnlyMapF, cell))
  182. fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  183. row := fromRow - 1
  184. col := TitleToNumber(fromCol)
  185. width = int(float64(width) * formatSet.XScale)
  186. height = int(float64(height) * formatSet.YScale)
  187. colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 := f.positionObjectPixels(sheet, col, row, formatSet.OffsetX, formatSet.OffsetY, width, height)
  188. content := xlsxWsDr{}
  189. content.A = NameSpaceDrawingML
  190. content.Xdr = NameSpaceDrawingMLSpreadSheet
  191. cNvPrID := f.drawingParser(drawingXML, &content)
  192. twoCellAnchor := xdrCellAnchor{}
  193. twoCellAnchor.EditAs = "oneCell"
  194. from := xlsxFrom{}
  195. from.Col = colStart
  196. from.ColOff = formatSet.OffsetX * EMU
  197. from.Row = rowStart
  198. from.RowOff = formatSet.OffsetY * EMU
  199. to := xlsxTo{}
  200. to.Col = colEnd
  201. to.ColOff = x2 * EMU
  202. to.Row = rowEnd
  203. to.RowOff = y2 * EMU
  204. twoCellAnchor.From = &from
  205. twoCellAnchor.To = &to
  206. pic := xlsxPic{}
  207. pic.NvPicPr.CNvPicPr.PicLocks.NoChangeAspect = formatSet.NoChangeAspect
  208. pic.NvPicPr.CNvPr.ID = f.countCharts() + f.countMedia() + 1
  209. pic.NvPicPr.CNvPr.Descr = file
  210. pic.NvPicPr.CNvPr.Name = "Picture " + strconv.Itoa(cNvPrID)
  211. pic.BlipFill.Blip.R = SourceRelationship
  212. pic.BlipFill.Blip.Embed = "rId" + strconv.Itoa(rID)
  213. pic.SpPr.PrstGeom.Prst = "rect"
  214. twoCellAnchor.Pic = &pic
  215. twoCellAnchor.ClientData = &xdrClientData{
  216. FLocksWithSheet: formatSet.FLocksWithSheet,
  217. FPrintsWithSheet: formatSet.FPrintsWithSheet,
  218. }
  219. content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
  220. output, _ := xml.Marshal(content)
  221. f.saveFileList(drawingXML, string(output))
  222. }
  223. // addDrawingRelationships provides function to add image part relationships in
  224. // the file xl/drawings/_rels/drawing%d.xml.rels by given drawing index,
  225. // relationship type and target.
  226. func (f *File) addDrawingRelationships(index int, relType, target string) int {
  227. var rels = "xl/drawings/_rels/drawing" + strconv.Itoa(index) + ".xml.rels"
  228. var drawingRels xlsxWorkbookRels
  229. var rID = 1
  230. var ID bytes.Buffer
  231. ID.WriteString("rId")
  232. ID.WriteString(strconv.Itoa(rID))
  233. _, ok := f.XLSX[rels]
  234. if ok {
  235. ID.Reset()
  236. xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
  237. rID = len(drawingRels.Relationships) + 1
  238. ID.WriteString("rId")
  239. ID.WriteString(strconv.Itoa(rID))
  240. }
  241. drawingRels.Relationships = append(drawingRels.Relationships, xlsxWorkbookRelation{
  242. ID: ID.String(),
  243. Type: relType,
  244. Target: target,
  245. })
  246. output, _ := xml.Marshal(drawingRels)
  247. f.saveFileList(rels, string(output))
  248. return rID
  249. }
  250. // countMedia provides function to get media files count storage in the folder
  251. // xl/media/image.
  252. func (f *File) countMedia() int {
  253. count := 0
  254. for k := range f.XLSX {
  255. if strings.Contains(k, "xl/media/image") {
  256. count++
  257. }
  258. }
  259. return count
  260. }
  261. // addMedia provides function to add picture into folder xl/media/image by given
  262. // file name and extension name.
  263. func (f *File) addMedia(file, ext string) {
  264. count := f.countMedia()
  265. dat, _ := ioutil.ReadFile(file)
  266. media := "xl/media/image" + strconv.Itoa(count+1) + ext
  267. f.XLSX[media] = string(dat)
  268. }
  269. // setContentTypePartImageExtensions provides function to set the content type
  270. // for relationship parts and the Main Document part.
  271. func (f *File) setContentTypePartImageExtensions() {
  272. var imageTypes = map[string]bool{"jpeg": false, "png": false, "gif": false}
  273. content := f.contentTypesReader()
  274. for _, v := range content.Defaults {
  275. _, ok := imageTypes[v.Extension]
  276. if ok {
  277. imageTypes[v.Extension] = true
  278. }
  279. }
  280. for k, v := range imageTypes {
  281. if !v {
  282. content.Defaults = append(content.Defaults, xlsxDefault{
  283. Extension: k,
  284. ContentType: "image/" + k,
  285. })
  286. }
  287. }
  288. }
  289. // setContentTypePartVMLExtensions provides function to set the content type
  290. // for relationship parts and the Main Document part.
  291. func (f *File) setContentTypePartVMLExtensions() {
  292. vml := false
  293. content := f.contentTypesReader()
  294. for _, v := range content.Defaults {
  295. if v.Extension == "vml" {
  296. vml = true
  297. }
  298. }
  299. if !vml {
  300. content.Defaults = append(content.Defaults, xlsxDefault{
  301. Extension: "vml",
  302. ContentType: "application/vnd.openxmlformats-officedocument.vmlDrawing",
  303. })
  304. }
  305. }
  306. // addContentTypePart provides function to add content type part relationships
  307. // in the file [Content_Types].xml by given index.
  308. func (f *File) addContentTypePart(index int, contentType string) {
  309. setContentType := map[string]func(){
  310. "comments": f.setContentTypePartVMLExtensions,
  311. "drawings": f.setContentTypePartImageExtensions,
  312. }
  313. partNames := map[string]string{
  314. "chart": "/xl/charts/chart" + strconv.Itoa(index) + ".xml",
  315. "comments": "/xl/comments" + strconv.Itoa(index) + ".xml",
  316. "drawings": "/xl/drawings/drawing" + strconv.Itoa(index) + ".xml",
  317. "table": "/xl/tables/table" + strconv.Itoa(index) + ".xml",
  318. }
  319. contentTypes := map[string]string{
  320. "chart": "application/vnd.openxmlformats-officedocument.drawingml.chart+xml",
  321. "comments": "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
  322. "drawings": "application/vnd.openxmlformats-officedocument.drawing+xml",
  323. "table": "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",
  324. }
  325. s, ok := setContentType[contentType]
  326. if ok {
  327. s()
  328. }
  329. content := f.contentTypesReader()
  330. for _, v := range content.Overrides {
  331. if v.PartName == partNames[contentType] {
  332. return
  333. }
  334. }
  335. content.Overrides = append(content.Overrides, xlsxOverride{
  336. PartName: partNames[contentType],
  337. ContentType: contentTypes[contentType],
  338. })
  339. }
  340. // getSheetRelationshipsTargetByID provides function to get Target attribute
  341. // value in xl/worksheets/_rels/sheet%d.xml.rels by given sheet name and
  342. // relationship index.
  343. func (f *File) getSheetRelationshipsTargetByID(sheet, rID string) string {
  344. var rels = "xl/worksheets/_rels/" + strings.ToLower(sheet) + ".xml.rels"
  345. var sheetRels xlsxWorkbookRels
  346. xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
  347. for _, v := range sheetRels.Relationships {
  348. if v.ID == rID {
  349. return v.Target
  350. }
  351. }
  352. return ""
  353. }
  354. // GetPicture provides function to get picture base name and raw content embed
  355. // in XLSX by given worksheet and cell name. This function returns the file name
  356. // in XLSX and file contents as []byte data types. For example:
  357. //
  358. // xlsx, err := excelize.OpenFile("./Workbook.xlsx")
  359. // if err != nil {
  360. // fmt.Println(err)
  361. // os.Exit(1)
  362. // }
  363. // file, raw := xlsx.GetPicture("Sheet1", "A2")
  364. // if file == "" {
  365. // os.Exit(1)
  366. // }
  367. // err := ioutil.WriteFile(file, raw, 0644)
  368. // if err != nil {
  369. // fmt.Println(err)
  370. // os.Exit(1)
  371. // }
  372. //
  373. func (f *File) GetPicture(sheet, cell string) (string, []byte) {
  374. xlsx := f.workSheetReader(sheet)
  375. if xlsx.Drawing == nil {
  376. return "", []byte{}
  377. }
  378. target := f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
  379. drawingXML := strings.Replace(target, "..", "xl", -1)
  380. _, ok := f.XLSX[drawingXML]
  381. if !ok {
  382. return "", []byte{}
  383. }
  384. decodeWsDr := decodeWsDr{}
  385. xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
  386. cell = strings.ToUpper(cell)
  387. fromCol := string(strings.Map(letterOnlyMapF, cell))
  388. fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  389. row := fromRow - 1
  390. col := TitleToNumber(fromCol)
  391. drawingRelationships := strings.Replace(strings.Replace(target, "../drawings", "xl/drawings/_rels", -1), ".xml", ".xml.rels", -1)
  392. for _, anchor := range decodeWsDr.TwoCellAnchor {
  393. decodeTwoCellAnchor := decodeTwoCellAnchor{}
  394. xml.Unmarshal([]byte("<decodeTwoCellAnchor>"+anchor.Content+"</decodeTwoCellAnchor>"), &decodeTwoCellAnchor)
  395. if decodeTwoCellAnchor.From == nil || decodeTwoCellAnchor.Pic == nil {
  396. continue
  397. }
  398. if decodeTwoCellAnchor.From.Col == col && decodeTwoCellAnchor.From.Row == row {
  399. xlsxWorkbookRelation := f.getDrawingRelationships(drawingRelationships, decodeTwoCellAnchor.Pic.BlipFill.Blip.Embed)
  400. _, ok := supportImageTypes[filepath.Ext(xlsxWorkbookRelation.Target)]
  401. if !ok {
  402. continue
  403. }
  404. return filepath.Base(xlsxWorkbookRelation.Target), []byte(f.XLSX[strings.Replace(xlsxWorkbookRelation.Target, "..", "xl", -1)])
  405. }
  406. }
  407. return "", []byte{}
  408. }
  409. // getDrawingRelationships provides function to get drawing relationships from
  410. // xl/drawings/_rels/drawing%s.xml.rels by given file name and relationship ID.
  411. func (f *File) getDrawingRelationships(rels, rID string) *xlsxWorkbookRelation {
  412. _, ok := f.XLSX[rels]
  413. if !ok {
  414. return nil
  415. }
  416. var drawingRels xlsxWorkbookRels
  417. xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
  418. for _, v := range drawingRels.Relationships {
  419. if v.ID != rID {
  420. continue
  421. }
  422. return &v
  423. }
  424. return nil
  425. }