shape.go 15 KB

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