picture.go 14 KB

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