picture.go 15 KB

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