shape.go 14 KB

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