shape.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. // Copyright 2016 - 2020 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.10 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. // err := f.AddShape("Sheet1", "G6", `{"type":"rect","color":{"line":"#4286F4","fill":"#8eb9ff"},"paragraph":[{"text":"Rectangle Shape","font":{"bold":true,"italic":true,"family":"Times New Roman","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, err := f.workSheetReader(sheet)
  259. if err != nil {
  260. return err
  261. }
  262. // Add first shape for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
  263. drawingID := f.countDrawings() + 1
  264. drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  265. sheetRelationshipsDrawingXML := "../drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
  266. if xlsx.Drawing != nil {
  267. // The worksheet already has a shape or chart relationships, use the relationships drawing ../drawings/drawing%d.xml.
  268. sheetRelationshipsDrawingXML = f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
  269. drawingID, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(sheetRelationshipsDrawingXML, "../drawings/drawing"), ".xml"))
  270. drawingXML = strings.Replace(sheetRelationshipsDrawingXML, "..", "xl", -1)
  271. } else {
  272. // Add first shape for given sheet.
  273. sheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(f.sheetMap[trimSheetName(sheet)], "xl/worksheets/") + ".rels"
  274. rID := f.addRels(sheetRels, SourceRelationshipDrawingML, sheetRelationshipsDrawingXML, "")
  275. f.addSheetDrawing(sheet, rID)
  276. }
  277. err = f.addDrawingShape(sheet, drawingXML, cell, formatSet)
  278. if err != nil {
  279. return err
  280. }
  281. f.addContentTypePart(drawingID, "drawings")
  282. return err
  283. }
  284. // addDrawingShape provides a function to add preset geometry by given sheet,
  285. // drawingXMLand format sets.
  286. func (f *File) addDrawingShape(sheet, drawingXML, cell string, formatSet *formatShape) error {
  287. fromCol, fromRow, err := CellNameToCoordinates(cell)
  288. if err != nil {
  289. return err
  290. }
  291. colIdx := fromCol - 1
  292. rowIdx := fromRow - 1
  293. textUnderlineType := map[string]bool{
  294. "none": true,
  295. "words": true,
  296. "sng": true,
  297. "dbl": true,
  298. "heavy": true,
  299. "dotted": true,
  300. "dottedHeavy": true,
  301. "dash": true,
  302. "dashHeavy": true,
  303. "dashLong": true,
  304. "dashLongHeavy": true,
  305. "dotDash": true,
  306. "dotDashHeavy": true,
  307. "dotDotDash": true,
  308. "dotDotDashHeavy": true,
  309. "wavy": true,
  310. "wavyHeavy": true,
  311. "wavyDbl": true,
  312. }
  313. width := int(float64(formatSet.Width) * formatSet.Format.XScale)
  314. height := int(float64(formatSet.Height) * formatSet.Format.YScale)
  315. colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 :=
  316. f.positionObjectPixels(sheet, colIdx, rowIdx, formatSet.Format.OffsetX, formatSet.Format.OffsetY,
  317. width, height)
  318. content, cNvPrID := f.drawingParser(drawingXML)
  319. twoCellAnchor := xdrCellAnchor{}
  320. twoCellAnchor.EditAs = formatSet.Format.Positioning
  321. from := xlsxFrom{}
  322. from.Col = colStart
  323. from.ColOff = formatSet.Format.OffsetX * EMU
  324. from.Row = rowStart
  325. from.RowOff = formatSet.Format.OffsetY * EMU
  326. to := xlsxTo{}
  327. to.Col = colEnd
  328. to.ColOff = x2 * EMU
  329. to.Row = rowEnd
  330. to.RowOff = y2 * EMU
  331. twoCellAnchor.From = &from
  332. twoCellAnchor.To = &to
  333. shape := xdrSp{
  334. NvSpPr: &xdrNvSpPr{
  335. CNvPr: &xlsxCNvPr{
  336. ID: cNvPrID,
  337. Name: "Shape " + strconv.Itoa(cNvPrID),
  338. },
  339. CNvSpPr: &xdrCNvSpPr{
  340. TxBox: true,
  341. },
  342. },
  343. SpPr: &xlsxSpPr{
  344. PrstGeom: xlsxPrstGeom{
  345. Prst: formatSet.Type,
  346. },
  347. },
  348. Style: &xdrStyle{
  349. LnRef: setShapeRef(formatSet.Color.Line, 2),
  350. FillRef: setShapeRef(formatSet.Color.Fill, 1),
  351. EffectRef: setShapeRef(formatSet.Color.Effect, 0),
  352. FontRef: &aFontRef{
  353. Idx: "minor",
  354. SchemeClr: &attrValString{
  355. Val: stringPtr("tx1"),
  356. },
  357. },
  358. },
  359. TxBody: &xdrTxBody{
  360. BodyPr: &aBodyPr{
  361. VertOverflow: "clip",
  362. HorzOverflow: "clip",
  363. Wrap: "none",
  364. RtlCol: false,
  365. Anchor: "t",
  366. },
  367. },
  368. }
  369. if len(formatSet.Paragraph) < 1 {
  370. formatSet.Paragraph = []formatShapeParagraph{
  371. {
  372. Font: Font{
  373. Bold: false,
  374. Italic: false,
  375. Underline: "none",
  376. Family: f.GetDefaultFont(),
  377. Size: 11,
  378. Color: "#000000",
  379. },
  380. Text: " ",
  381. },
  382. }
  383. }
  384. for _, p := range formatSet.Paragraph {
  385. u := p.Font.Underline
  386. _, ok := textUnderlineType[u]
  387. if !ok {
  388. u = "none"
  389. }
  390. text := p.Text
  391. if text == "" {
  392. text = " "
  393. }
  394. paragraph := &aP{
  395. R: &aR{
  396. RPr: aRPr{
  397. I: p.Font.Italic,
  398. B: p.Font.Bold,
  399. Lang: "en-US",
  400. AltLang: "en-US",
  401. U: u,
  402. Sz: p.Font.Size * 100,
  403. Latin: &aLatin{Typeface: p.Font.Family},
  404. },
  405. T: text,
  406. },
  407. EndParaRPr: &aEndParaRPr{
  408. Lang: "en-US",
  409. },
  410. }
  411. srgbClr := strings.Replace(strings.ToUpper(p.Font.Color), "#", "", -1)
  412. if len(srgbClr) == 6 {
  413. paragraph.R.RPr.SolidFill = &aSolidFill{
  414. SrgbClr: &attrValString{
  415. Val: stringPtr(srgbClr),
  416. },
  417. }
  418. }
  419. shape.TxBody.P = append(shape.TxBody.P, paragraph)
  420. }
  421. twoCellAnchor.Sp = &shape
  422. twoCellAnchor.ClientData = &xdrClientData{
  423. FLocksWithSheet: formatSet.Format.FLocksWithSheet,
  424. FPrintsWithSheet: formatSet.Format.FPrintsWithSheet,
  425. }
  426. content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
  427. f.Drawings[drawingXML] = content
  428. return err
  429. }
  430. // setShapeRef provides a function to set color with hex model by given actual
  431. // color value.
  432. func setShapeRef(color string, i int) *aRef {
  433. if color == "" {
  434. return &aRef{
  435. Idx: 0,
  436. ScrgbClr: &aScrgbClr{
  437. R: 0,
  438. G: 0,
  439. B: 0,
  440. },
  441. }
  442. }
  443. return &aRef{
  444. Idx: i,
  445. SrgbClr: &attrValString{
  446. Val: stringPtr(strings.Replace(strings.ToUpper(color), "#", "", -1)),
  447. },
  448. }
  449. }