shape.go 15 KB

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