shape.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. package excelize
  2. import (
  3. "encoding/json"
  4. "encoding/xml"
  5. "strconv"
  6. "strings"
  7. )
  8. // parseFormatShapeSet provides function to parse the format settings of the
  9. // shape with default value.
  10. func parseFormatShapeSet(formatSet string) *formatShape {
  11. format := formatShape{
  12. Width: 160,
  13. Height: 160,
  14. Format: formatPicture{
  15. FPrintsWithSheet: true,
  16. FLocksWithSheet: false,
  17. NoChangeAspect: false,
  18. OffsetX: 0,
  19. OffsetY: 0,
  20. XScale: 1.0,
  21. YScale: 1.0,
  22. },
  23. Font: formatFont{
  24. Bold: false,
  25. Italic: false,
  26. Underline: "none",
  27. Family: "Calibri",
  28. Size: 11,
  29. Color: "#000000",
  30. },
  31. Text: " ",
  32. }
  33. json.Unmarshal([]byte(formatSet), &format)
  34. return &format
  35. }
  36. // AddShape provides the method to add shape in a sheet by given worksheet
  37. // index, shape format set (such as offset, scale, aspect ratio setting and
  38. // print settings) and properties set. For example, add text box (rect shape) in
  39. // Sheet1:
  40. //
  41. // xlsx.AddShape("Sheet1", "G6", `{"type":"rect", "text":"Rectangle Shape", "color":{"line":"#4286F4","fill":"#8eb9ff"}, "font":{"bold":true,"italic":true,"family":"Berlin Sans FB Demi","size":36,"color":"#777777","underline":"sng"}, "width": 180, "height": 90}`)
  42. //
  43. // The following shows the type of chart supported by excelize:
  44. //
  45. // accentBorderCallout1 (Callout 1 with Border and Accent Shape)
  46. // accentBorderCallout2 (Callout 2 with Border and Accent Shape)
  47. // accentBorderCallout3 (Callout 3 with Border and Accent Shape)
  48. // accentCallout1 (Callout 1 Shape)
  49. // accentCallout2 (Callout 2 Shape)
  50. // accentCallout3 (Callout 3 Shape)
  51. // actionButtonBackPrevious (Back or Previous Button Shape)
  52. // actionButtonBeginning (Beginning Button Shape)
  53. // actionButtonBlank (Blank Button Shape)
  54. // actionButtonDocument (Document Button Shape)
  55. // actionButtonEnd (End Button Shape)
  56. // actionButtonForwardNext (Forward or Next Button Shape)
  57. // actionButtonHelp (Help Button Shape)
  58. // actionButtonHome (Home Button Shape)
  59. // actionButtonInformation (Information Button Shape)
  60. // actionButtonMovie (Movie Button Shape)
  61. // actionButtonReturn (Return Button Shape)
  62. // actionButtonSound (Sound Button Shape)
  63. // arc (Curved Arc Shape)
  64. // bentArrow (Bent Arrow Shape)
  65. // bentConnector2 (Bent Connector 2 Shape)
  66. // bentConnector3 (Bent Connector 3 Shape)
  67. // bentConnector4 (Bent Connector 4 Shape)
  68. // bentConnector5 (Bent Connector 5 Shape)
  69. // bentUpArrow (Bent Up Arrow Shape)
  70. // bevel (Bevel Shape)
  71. // blockArc (Block Arc Shape)
  72. // borderCallout1 (Callout 1 with Border Shape)
  73. // borderCallout2 (Callout 2 with Border Shape)
  74. // borderCallout3 (Callout 3 with Border Shape)
  75. // bracePair (Brace Pair Shape)
  76. // bracketPair (Bracket Pair Shape)
  77. // callout1 (Callout 1 Shape)
  78. // callout2 (Callout 2 Shape)
  79. // callout3 (Callout 3 Shape)
  80. // can (Can Shape)
  81. // chartPlus (Chart Plus Shape)
  82. // chartStar (Chart Star Shape)
  83. // chartX (Chart X Shape)
  84. // chevron (Chevron Shape)
  85. // chord (Chord Shape)
  86. // circularArrow (Circular Arrow Shape)
  87. // cloud (Cloud Shape)
  88. // cloudCallout (Callout Cloud Shape)
  89. // corner (Corner Shape)
  90. // cornerTabs (Corner Tabs Shape)
  91. // cube (Cube Shape)
  92. // curvedConnector2 (Curved Connector 2 Shape)
  93. // curvedConnector3 (Curved Connector 3 Shape)
  94. // curvedConnector4 (Curved Connector 4 Shape)
  95. // curvedConnector5 (Curved Connector 5 Shape)
  96. // curvedDownArrow (Curved Down Arrow Shape)
  97. // curvedLeftArrow (Curved Left Arrow Shape)
  98. // curvedRightArrow (Curved Right Arrow Shape)
  99. // curvedUpArrow (Curved Up Arrow Shape)
  100. // decagon (Decagon Shape)
  101. // diagStripe (Diagonal Stripe Shape)
  102. // diamond (Diamond Shape)
  103. // dodecagon (Dodecagon Shape)
  104. // donut (Donut Shape)
  105. // doubleWave (Double Wave Shape)
  106. // downArrow (Down Arrow Shape)
  107. // downArrowCallout (Callout Down Arrow Shape)
  108. // ellipse (Ellipse Shape)
  109. // ellipseRibbon (Ellipse Ribbon Shape)
  110. // ellipseRibbon2 (Ellipse Ribbon 2 Shape)
  111. // flowChartAlternateProcess (Alternate Process Flow Shape)
  112. // flowChartCollate (Collate Flow Shape)
  113. // flowChartConnector (Connector Flow Shape)
  114. // flowChartDecision (Decision Flow Shape)
  115. // flowChartDelay (Delay Flow Shape)
  116. // flowChartDisplay (Display Flow Shape)
  117. // flowChartDocument (Document Flow Shape)
  118. // flowChartExtract (Extract Flow Shape)
  119. // flowChartInputOutput (Input Output Flow Shape)
  120. // flowChartInternalStorage (Internal Storage Flow Shape)
  121. // flowChartMagneticDisk (Magnetic Disk Flow Shape)
  122. // flowChartMagneticDrum (Magnetic Drum Flow Shape)
  123. // flowChartMagneticTape (Magnetic Tape Flow Shape)
  124. // flowChartManualInput (Manual Input Flow Shape)
  125. // flowChartManualOperation (Manual Operation Flow Shape)
  126. // flowChartMerge (Merge Flow Shape)
  127. // flowChartMultidocument (Multi-Document Flow Shape)
  128. // flowChartOfflineStorage (Offline Storage Flow Shape)
  129. // flowChartOffpageConnector (Off-Page Connector Flow Shape)
  130. // flowChartOnlineStorage (Online Storage Flow Shape)
  131. // flowChartOr (Or Flow Shape)
  132. // flowChartPredefinedProcess (Predefined Process Flow Shape)
  133. // flowChartPreparation (Preparation Flow Shape)
  134. // flowChartProcess (Process Flow Shape)
  135. // flowChartPunchedCard (Punched Card Flow Shape)
  136. // flowChartPunchedTape (Punched Tape Flow Shape)
  137. // flowChartSort (Sort Flow Shape)
  138. // flowChartSummingJunction (Summing Junction Flow Shape)
  139. // flowChartTerminator (Terminator Flow Shape)
  140. // foldedCorner (Folded Corner Shape)
  141. // frame (Frame Shape)
  142. // funnel (Funnel Shape)
  143. // gear6 (Gear 6 Shape)
  144. // gear9 (Gear 9 Shape)
  145. // halfFrame (Half Frame Shape)
  146. // heart (Heart Shape)
  147. // heptagon (Heptagon Shape)
  148. // hexagon (Hexagon Shape)
  149. // homePlate (Home Plate Shape)
  150. // horizontalScroll (Horizontal Scroll Shape)
  151. // irregularSeal1 (Irregular Seal 1 Shape)
  152. // irregularSeal2 (Irregular Seal 2 Shape)
  153. // leftArrow (Left Arrow Shape)
  154. // leftArrowCallout (Callout Left Arrow Shape)
  155. // leftBrace (Left Brace Shape)
  156. // leftBracket (Left Bracket Shape)
  157. // leftCircularArrow (Left Circular Arrow Shape)
  158. // leftRightArrow (Left Right Arrow Shape)
  159. // leftRightArrowCallout (Callout Left Right Arrow Shape)
  160. // leftRightCircularArrow (Left Right Circular Arrow Shape)
  161. // leftRightRibbon (Left Right Ribbon Shape)
  162. // leftRightUpArrow (Left Right Up Arrow Shape)
  163. // leftUpArrow (Left Up Arrow Shape)
  164. // lightningBolt (Lightning Bolt Shape)
  165. // line (Line Shape)
  166. // lineInv (Line Inverse Shape)
  167. // mathDivide (Divide Math Shape)
  168. // mathEqual (Equal Math Shape)
  169. // mathMinus (Minus Math Shape)
  170. // mathMultiply (Multiply Math Shape)
  171. // mathNotEqual (Not Equal Math Shape)
  172. // mathPlus (Plus Math Shape)
  173. // moon (Moon Shape)
  174. // nonIsoscelesTrapezoid (Non-Isosceles Trapezoid Shape)
  175. // noSmoking (No Smoking Shape)
  176. // notchedRightArrow (Notched Right Arrow Shape)
  177. // octagon (Octagon Shape)
  178. // parallelogram (Parallelogram Shape)
  179. // pentagon (Pentagon Shape)
  180. // pie (Pie Shape)
  181. // pieWedge (Pie Wedge Shape)
  182. // plaque (Plaque Shape)
  183. // plaqueTabs (Plaque Tabs Shape)
  184. // plus (Plus Shape)
  185. // quadArrow (Quad-Arrow Shape)
  186. // quadArrowCallout (Callout Quad-Arrow Shape)
  187. // rect (Rectangle Shape)
  188. // ribbon (Ribbon Shape)
  189. // ribbon2 (Ribbon 2 Shape)
  190. // rightArrow (Right Arrow Shape)
  191. // rightArrowCallout (Callout Right Arrow Shape)
  192. // rightBrace (Right Brace Shape)
  193. // rightBracket (Right Bracket Shape)
  194. // round1Rect (One Round Corner Rectangle Shape)
  195. // round2DiagRect (Two Diagonal Round Corner Rectangle Shape)
  196. // round2SameRect (Two Same-side Round Corner Rectangle Shape)
  197. // roundRect (Round Corner Rectangle Shape)
  198. // rtTriangle (Right Triangle Shape)
  199. // smileyFace (Smiley Face Shape)
  200. // snip1Rect (One Snip Corner Rectangle Shape)
  201. // snip2DiagRect (Two Diagonal Snip Corner Rectangle Shape)
  202. // snip2SameRect (Two Same-side Snip Corner Rectangle Shape)
  203. // snipRoundRect (One Snip One Round Corner Rectangle Shape)
  204. // squareTabs (Square Tabs Shape)
  205. // star10 (Ten Pointed Star Shape)
  206. // star12 (Twelve Pointed Star Shape)
  207. // star16 (Sixteen Pointed Star Shape)
  208. // star24 (Twenty Four Pointed Star Shape)
  209. // star32 (Thirty Two Pointed Star Shape)
  210. // star4 (Four Pointed Star Shape)
  211. // star5 (Five Pointed Star Shape)
  212. // star6 (Six Pointed Star Shape)
  213. // star7 (Seven Pointed Star Shape)
  214. // star8 (Eight Pointed Star Shape)
  215. // straightConnector1 (Straight Connector 1 Shape)
  216. // stripedRightArrow (Striped Right Arrow Shape)
  217. // sun (Sun Shape)
  218. // swooshArrow (Swoosh Arrow Shape)
  219. // teardrop (Teardrop Shape)
  220. // trapezoid (Trapezoid Shape)
  221. // triangle (Triangle Shape)
  222. // upArrow (Up Arrow Shape)
  223. // upArrowCallout (Callout Up Arrow Shape)
  224. // upDownArrow (Up Down Arrow Shape)
  225. // upDownArrowCallout (Callout Up Down Arrow Shape)
  226. // uturnArrow (U-Turn Arrow Shape)
  227. // verticalScroll (Vertical Scroll Shape)
  228. // wave (Wave Shape)
  229. // wedgeEllipseCallout (Callout Wedge Ellipse Shape)
  230. // wedgeRectCallout (Callout Wedge Rectangle Shape)
  231. // wedgeRoundRectCallout (Callout Wedge Round Rectangle Shape)
  232. //
  233. // The following shows the type of text underline supported by excelize:
  234. //
  235. // none
  236. // words
  237. // sng
  238. // dbl
  239. // heavy
  240. // dotted
  241. // dottedHeavy
  242. // dash
  243. // dashHeavy
  244. // dashLong
  245. // dashLongHeavy
  246. // dotDash
  247. // dotDashHeavy
  248. // dotDotDash
  249. // dotDotDashHeavy
  250. // wavy
  251. // wavyHeavy
  252. // wavyDbl
  253. //
  254. func (f *File) AddShape(sheet, cell, format string) {
  255. formatSet := parseFormatShapeSet(format)
  256. // Read sheet data.
  257. xlsx := f.workSheetReader(sheet)
  258. // Add first shape for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
  259. drawingID := f.countDrawings() + 1
  260. drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  261. sheetRelationshipsDrawingXML := "../drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  262. if xlsx.Drawing != nil {
  263. // The worksheet already has a shape or chart relationships, use the relationships drawing ../drawings/drawing%d.xml.
  264. sheetRelationshipsDrawingXML = f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
  265. drawingID, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(sheetRelationshipsDrawingXML, "../drawings/drawing"), ".xml"))
  266. drawingXML = strings.Replace(sheetRelationshipsDrawingXML, "..", "xl", -1)
  267. } else {
  268. // Add first shape for given sheet.
  269. rID := f.addSheetRelationships(sheet, SourceRelationshipDrawingML, sheetRelationshipsDrawingXML, "")
  270. f.addSheetDrawing(sheet, rID)
  271. }
  272. f.addDrawingShape(sheet, drawingXML, cell, formatSet)
  273. f.addDrawingContentTypePart(drawingID)
  274. }
  275. // addDrawingShape
  276. func (f *File) addDrawingShape(sheet, drawingXML, cell string, formatSet *formatShape) {
  277. textUnderlineType := map[string]bool{"none": true, "words": true, "sng": true, "dbl": true, "heavy": true, "dotted": true, "dottedHeavy": true, "dash": true, "dashHeavy": true, "dashLong": true, "dashLongHeavy": true, "dotDash": true, "dotDashHeavy": true, "dotDotDash": true, "dotDotDashHeavy": true, "wavy": true, "wavyHeavy": true, "wavyDbl": true}
  278. u := formatSet.Font.Underline
  279. _, ok := textUnderlineType[u]
  280. if !ok {
  281. u = "none"
  282. }
  283. cell = strings.ToUpper(cell)
  284. fromCol := string(strings.Map(letterOnlyMapF, cell))
  285. fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  286. row := fromRow - 1
  287. col := titleToNumber(fromCol)
  288. width := int(float64(formatSet.Width) * formatSet.Format.XScale)
  289. height := int(float64(formatSet.Height) * formatSet.Format.YScale)
  290. colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 := f.positionObjectPixels(sheet, col, row, formatSet.Format.OffsetX, formatSet.Format.OffsetY, width, height)
  291. content := xlsxWsDr{}
  292. content.A = NameSpaceDrawingML
  293. content.Xdr = NameSpaceDrawingMLSpreadSheet
  294. cNvPrID := 1
  295. _, ok = f.XLSX[drawingXML]
  296. if ok { // Append Model
  297. decodeWsDr := decodeWsDr{}
  298. xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
  299. cNvPrID = len(decodeWsDr.OneCellAnchor) + len(decodeWsDr.TwoCellAnchor) + 1
  300. for _, v := range decodeWsDr.OneCellAnchor {
  301. content.OneCellAnchor = append(content.OneCellAnchor, &xdrCellAnchor{
  302. EditAs: v.EditAs,
  303. GraphicFrame: v.Content,
  304. })
  305. }
  306. for _, v := range decodeWsDr.TwoCellAnchor {
  307. content.TwoCellAnchor = append(content.TwoCellAnchor, &xdrCellAnchor{
  308. EditAs: v.EditAs,
  309. GraphicFrame: v.Content,
  310. })
  311. }
  312. }
  313. twoCellAnchor := xdrCellAnchor{}
  314. twoCellAnchor.EditAs = "oneCell"
  315. from := xlsxFrom{}
  316. from.Col = colStart
  317. from.ColOff = formatSet.Format.OffsetX * EMU
  318. from.Row = rowStart
  319. from.RowOff = formatSet.Format.OffsetY * EMU
  320. to := xlsxTo{}
  321. to.Col = colEnd
  322. to.ColOff = x2 * EMU
  323. to.Row = rowEnd
  324. to.RowOff = y2 * EMU
  325. twoCellAnchor.From = &from
  326. twoCellAnchor.To = &to
  327. shape := xdrSp{
  328. NvSpPr: &xdrNvSpPr{
  329. CNvPr: &xlsxCNvPr{
  330. ID: cNvPrID,
  331. Name: "Shape " + strconv.Itoa(cNvPrID),
  332. },
  333. CNvSpPr: &xdrCNvSpPr{
  334. TxBox: true,
  335. },
  336. },
  337. SpPr: &xlsxSpPr{
  338. PrstGeom: xlsxPrstGeom{
  339. Prst: formatSet.Type,
  340. },
  341. },
  342. Style: &xdrStyle{
  343. LnRef: setShapeRef(formatSet.Color.Line, 2),
  344. FillRef: setShapeRef(formatSet.Color.Fill, 1),
  345. EffectRef: setShapeRef(formatSet.Color.Effect, 0),
  346. FontRef: &aFontRef{
  347. Idx: "minor",
  348. SchemeClr: &attrValString{
  349. Val: "tx1",
  350. },
  351. },
  352. },
  353. TxBody: &xdrTxBody{
  354. BodyPr: &aBodyPr{
  355. VertOverflow: "clip",
  356. HorzOverflow: "clip",
  357. Wrap: "none",
  358. RtlCol: false,
  359. Anchor: "t",
  360. },
  361. P: &aP{
  362. R: &aR{
  363. RPr: aRPr{
  364. I: formatSet.Font.Italic,
  365. B: formatSet.Font.Bold,
  366. Lang: "en-US",
  367. AltLang: "en-US",
  368. U: u,
  369. Sz: formatSet.Font.Size * 100,
  370. Latin: &aLatin{Typeface: formatSet.Font.Family},
  371. SolidFill: &aSolidFill{
  372. SrgbClr: &attrValString{
  373. Val: strings.Replace(strings.ToUpper(formatSet.Font.Color), "#", "", -1),
  374. },
  375. },
  376. },
  377. T: formatSet.Text,
  378. },
  379. EndParaRPr: &aEndParaRPr{
  380. Lang: "en-US",
  381. },
  382. },
  383. },
  384. }
  385. twoCellAnchor.Sp = &shape
  386. twoCellAnchor.ClientData = &xdrClientData{
  387. FLocksWithSheet: formatSet.Format.FLocksWithSheet,
  388. FPrintsWithSheet: formatSet.Format.FPrintsWithSheet,
  389. }
  390. content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
  391. output, _ := xml.Marshal(content)
  392. f.saveFileList(drawingXML, string(output))
  393. }
  394. // setShapeRef provides function to set color with hex model by given actual
  395. // color value.
  396. func setShapeRef(color string, i int) *aRef {
  397. if color == "" {
  398. return &aRef{
  399. Idx: 0,
  400. ScrgbClr: &aScrgbClr{
  401. R: 0,
  402. G: 0,
  403. B: 0,
  404. },
  405. }
  406. }
  407. return &aRef{
  408. Idx: i,
  409. SrgbClr: &attrValString{
  410. Val: strings.Replace(strings.ToUpper(color), "#", "", -1),
  411. },
  412. }
  413. }