shape.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. package excelize
  2. import (
  3. "encoding/json"
  4. "encoding/xml"
  5. "strconv"
  6. "strings"
  7. )
  8. // parseFormatShapeSet provides a function to parse the format settings of the
  9. // shape with default value.
  10. func parseFormatShapeSet(formatSet string) (*formatShape, error) {
  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. err := json.Unmarshal([]byte(formatSet), &format)
  25. return &format, err
  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)
  30. // in 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) error {
  246. formatSet, err := parseFormatShapeSet(format)
  247. if err != nil {
  248. return err
  249. }
  250. // Read sheet data.
  251. xlsx := f.workSheetReader(sheet)
  252. // Add first shape for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
  253. drawingID := f.countDrawings() + 1
  254. drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  255. sheetRelationshipsDrawingXML := "../drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  256. if xlsx.Drawing != nil {
  257. // The worksheet already has a shape or chart relationships, use the relationships drawing ../drawings/drawing%d.xml.
  258. sheetRelationshipsDrawingXML = f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
  259. drawingID, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(sheetRelationshipsDrawingXML, "../drawings/drawing"), ".xml"))
  260. drawingXML = strings.Replace(sheetRelationshipsDrawingXML, "..", "xl", -1)
  261. } else {
  262. // Add first shape for given sheet.
  263. rID := f.addSheetRelationships(sheet, SourceRelationshipDrawingML, sheetRelationshipsDrawingXML, "")
  264. f.addSheetDrawing(sheet, rID)
  265. }
  266. f.addDrawingShape(sheet, drawingXML, cell, formatSet)
  267. f.addContentTypePart(drawingID, "drawings")
  268. return err
  269. }
  270. // addDrawingShape provides a function to add preset geometry by given sheet,
  271. // drawingXMLand format sets.
  272. func (f *File) addDrawingShape(sheet, drawingXML, cell string, formatSet *formatShape) {
  273. 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}
  274. cell = strings.ToUpper(cell)
  275. fromCol := string(strings.Map(letterOnlyMapF, cell))
  276. fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  277. row := fromRow - 1
  278. col := TitleToNumber(fromCol)
  279. width := int(float64(formatSet.Width) * formatSet.Format.XScale)
  280. height := int(float64(formatSet.Height) * formatSet.Format.YScale)
  281. colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 := f.positionObjectPixels(sheet, col, row, formatSet.Format.OffsetX, formatSet.Format.OffsetY, width, height)
  282. content := xlsxWsDr{}
  283. content.A = NameSpaceDrawingML
  284. content.Xdr = NameSpaceDrawingMLSpreadSheet
  285. cNvPrID := f.drawingParser(drawingXML, &content)
  286. twoCellAnchor := xdrCellAnchor{}
  287. twoCellAnchor.EditAs = formatSet.Format.Positioning
  288. from := xlsxFrom{}
  289. from.Col = colStart
  290. from.ColOff = formatSet.Format.OffsetX * EMU
  291. from.Row = rowStart
  292. from.RowOff = formatSet.Format.OffsetY * EMU
  293. to := xlsxTo{}
  294. to.Col = colEnd
  295. to.ColOff = x2 * EMU
  296. to.Row = rowEnd
  297. to.RowOff = y2 * EMU
  298. twoCellAnchor.From = &from
  299. twoCellAnchor.To = &to
  300. shape := xdrSp{
  301. NvSpPr: &xdrNvSpPr{
  302. CNvPr: &xlsxCNvPr{
  303. ID: cNvPrID,
  304. Name: "Shape " + strconv.Itoa(cNvPrID),
  305. },
  306. CNvSpPr: &xdrCNvSpPr{
  307. TxBox: true,
  308. },
  309. },
  310. SpPr: &xlsxSpPr{
  311. PrstGeom: xlsxPrstGeom{
  312. Prst: formatSet.Type,
  313. },
  314. },
  315. Style: &xdrStyle{
  316. LnRef: setShapeRef(formatSet.Color.Line, 2),
  317. FillRef: setShapeRef(formatSet.Color.Fill, 1),
  318. EffectRef: setShapeRef(formatSet.Color.Effect, 0),
  319. FontRef: &aFontRef{
  320. Idx: "minor",
  321. SchemeClr: &attrValString{
  322. Val: "tx1",
  323. },
  324. },
  325. },
  326. TxBody: &xdrTxBody{
  327. BodyPr: &aBodyPr{
  328. VertOverflow: "clip",
  329. HorzOverflow: "clip",
  330. Wrap: "none",
  331. RtlCol: false,
  332. Anchor: "t",
  333. },
  334. },
  335. }
  336. if len(formatSet.Paragraph) < 1 {
  337. formatSet.Paragraph = []formatShapeParagraph{
  338. {
  339. Font: formatFont{
  340. Bold: false,
  341. Italic: false,
  342. Underline: "none",
  343. Family: "Calibri",
  344. Size: 11,
  345. Color: "#000000",
  346. },
  347. Text: " ",
  348. },
  349. }
  350. }
  351. for _, p := range formatSet.Paragraph {
  352. u := p.Font.Underline
  353. _, ok := textUnderlineType[u]
  354. if !ok {
  355. u = "none"
  356. }
  357. text := p.Text
  358. if text == "" {
  359. text = " "
  360. }
  361. paragraph := &aP{
  362. R: &aR{
  363. RPr: aRPr{
  364. I: p.Font.Italic,
  365. B: p.Font.Bold,
  366. Lang: "en-US",
  367. AltLang: "en-US",
  368. U: u,
  369. Sz: p.Font.Size * 100,
  370. Latin: &aLatin{Typeface: p.Font.Family},
  371. SolidFill: &aSolidFill{
  372. SrgbClr: &attrValString{
  373. Val: strings.Replace(strings.ToUpper(p.Font.Color), "#", "", -1),
  374. },
  375. },
  376. },
  377. T: text,
  378. },
  379. EndParaRPr: &aEndParaRPr{
  380. Lang: "en-US",
  381. },
  382. }
  383. shape.TxBody.P = append(shape.TxBody.P, paragraph)
  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, output)
  393. }
  394. // setShapeRef provides a 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. }