comment.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. "encoding/xml"
  13. "fmt"
  14. "strconv"
  15. "strings"
  16. )
  17. // parseFormatCommentsSet provides a function to parse the format settings of
  18. // the comment with default value.
  19. func parseFormatCommentsSet(formatSet string) (*formatComment, error) {
  20. format := formatComment{
  21. Author: "Author:",
  22. Text: " ",
  23. }
  24. err := json.Unmarshal([]byte(formatSet), &format)
  25. return &format, err
  26. }
  27. // GetComments retrieves all comments and returns a map of worksheet name to
  28. // the worksheet comments.
  29. func (f *File) GetComments() (comments map[string][]Comment) {
  30. comments = map[string][]Comment{}
  31. for n := range f.sheetMap {
  32. if d := f.commentsReader("xl" + strings.TrimPrefix(f.getSheetComments(f.GetSheetIndex(n)), "..")); d != nil {
  33. sheetComments := []Comment{}
  34. for _, comment := range d.CommentList.Comment {
  35. sheetComment := Comment{}
  36. if comment.AuthorID < len(d.Authors) {
  37. sheetComment.Author = d.Authors[comment.AuthorID].Author
  38. }
  39. sheetComment.Ref = comment.Ref
  40. sheetComment.AuthorID = comment.AuthorID
  41. for _, text := range comment.Text.R {
  42. sheetComment.Text += text.T
  43. }
  44. sheetComments = append(sheetComments, sheetComment)
  45. }
  46. comments[n] = sheetComments
  47. }
  48. }
  49. return
  50. }
  51. // getSheetComments provides the method to get the target comment reference by
  52. // given worksheet index.
  53. func (f *File) getSheetComments(sheetID int) string {
  54. var rels = "xl/worksheets/_rels/sheet" + strconv.Itoa(sheetID) + ".xml.rels"
  55. if sheetRels := f.workSheetRelsReader(rels); sheetRels != nil {
  56. for _, v := range sheetRels.Relationships {
  57. if v.Type == SourceRelationshipComments {
  58. return v.Target
  59. }
  60. }
  61. }
  62. return ""
  63. }
  64. // AddComment provides the method to add comment in a sheet by given worksheet
  65. // index, cell and format set (such as author and text). Note that the max
  66. // author length is 255 and the max text length is 32512. For example, add a
  67. // comment in Sheet1!$A$30:
  68. //
  69. // xlsx.AddComment("Sheet1", "A30", `{"author":"Excelize: ","text":"This is a comment."}`)
  70. //
  71. func (f *File) AddComment(sheet, cell, format string) error {
  72. formatSet, err := parseFormatCommentsSet(format)
  73. if err != nil {
  74. return err
  75. }
  76. // Read sheet data.
  77. xlsx := f.workSheetReader(sheet)
  78. commentID := f.countComments() + 1
  79. drawingVML := "xl/drawings/vmlDrawing" + strconv.Itoa(commentID) + ".vml"
  80. sheetRelationshipsComments := "../comments" + strconv.Itoa(commentID) + ".xml"
  81. sheetRelationshipsDrawingVML := "../drawings/vmlDrawing" + strconv.Itoa(commentID) + ".vml"
  82. if xlsx.LegacyDrawing != nil {
  83. // The worksheet already has a comments relationships, use the relationships drawing ../drawings/vmlDrawing%d.vml.
  84. sheetRelationshipsDrawingVML = f.getSheetRelationshipsTargetByID(sheet, xlsx.LegacyDrawing.RID)
  85. commentID, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(sheetRelationshipsDrawingVML, "../drawings/vmlDrawing"), ".vml"))
  86. drawingVML = strings.Replace(sheetRelationshipsDrawingVML, "..", "xl", -1)
  87. } else {
  88. // Add first comment for given sheet.
  89. rID := f.addSheetRelationships(sheet, SourceRelationshipDrawingVML, sheetRelationshipsDrawingVML, "")
  90. f.addSheetRelationships(sheet, SourceRelationshipComments, sheetRelationshipsComments, "")
  91. f.addSheetLegacyDrawing(sheet, rID)
  92. }
  93. commentsXML := "xl/comments" + strconv.Itoa(commentID) + ".xml"
  94. f.addComment(commentsXML, cell, formatSet)
  95. var colCount int
  96. for i, l := range strings.Split(formatSet.Text, "\n") {
  97. if ll := len(l); ll > colCount {
  98. if i == 0 {
  99. ll += len(formatSet.Author)
  100. }
  101. colCount = ll
  102. }
  103. }
  104. f.addDrawingVML(commentID, drawingVML, cell, strings.Count(formatSet.Text, "\n")+1, colCount)
  105. f.addContentTypePart(commentID, "comments")
  106. return err
  107. }
  108. // addDrawingVML provides a function to create comment as
  109. // xl/drawings/vmlDrawing%d.vml by given commit ID and cell.
  110. func (f *File) addDrawingVML(commentID int, drawingVML, cell string, lineCount, colCount int) {
  111. col, row := MustCellNameToCoordinates(cell)
  112. yAxis := col - 1
  113. xAxis := row - 1
  114. vml := f.VMLDrawing[drawingVML]
  115. if vml == nil {
  116. vml = &vmlDrawing{
  117. XMLNSv: "urn:schemas-microsoft-com:vml",
  118. XMLNSo: "urn:schemas-microsoft-com:office:office",
  119. XMLNSx: "urn:schemas-microsoft-com:office:excel",
  120. XMLNSmv: "http://macVmlSchemaUri",
  121. Shapelayout: &xlsxShapelayout{
  122. Ext: "edit",
  123. IDmap: &xlsxIDmap{
  124. Ext: "edit",
  125. Data: commentID,
  126. },
  127. },
  128. Shapetype: &xlsxShapetype{
  129. ID: "_x0000_t202",
  130. Coordsize: "21600,21600",
  131. Spt: 202,
  132. Path: "m0,0l0,21600,21600,21600,21600,0xe",
  133. Stroke: &xlsxStroke{
  134. Joinstyle: "miter",
  135. },
  136. VPath: &vPath{
  137. Gradientshapeok: "t",
  138. Connecttype: "miter",
  139. },
  140. },
  141. }
  142. }
  143. sp := encodeShape{
  144. Fill: &vFill{
  145. Color2: "#fbfe82",
  146. Angle: -180,
  147. Type: "gradient",
  148. Fill: &oFill{
  149. Ext: "view",
  150. Type: "gradientUnscaled",
  151. },
  152. },
  153. Shadow: &vShadow{
  154. On: "t",
  155. Color: "black",
  156. Obscured: "t",
  157. },
  158. Path: &vPath{
  159. Connecttype: "none",
  160. },
  161. Textbox: &vTextbox{
  162. Style: "mso-direction-alt:auto",
  163. Div: &xlsxDiv{
  164. Style: "text-align:left",
  165. },
  166. },
  167. ClientData: &xClientData{
  168. ObjectType: "Note",
  169. Anchor: fmt.Sprintf(
  170. "%d, 23, %d, 0, %d, %d, %d, 5",
  171. 1+yAxis, 1+xAxis, 2+yAxis+lineCount, colCount+yAxis, 2+xAxis+lineCount),
  172. AutoFill: "True",
  173. Row: xAxis,
  174. Column: yAxis,
  175. },
  176. }
  177. s, _ := xml.Marshal(sp)
  178. shape := xlsxShape{
  179. ID: "_x0000_s1025",
  180. Type: "#_x0000_t202",
  181. Style: "position:absolute;73.5pt;width:108pt;height:59.25pt;z-index:1;visibility:hidden",
  182. Fillcolor: "#fbf6d6",
  183. Strokecolor: "#edeaa1",
  184. Val: string(s[13 : len(s)-14]),
  185. }
  186. d := f.decodeVMLDrawingReader(drawingVML)
  187. if d != nil {
  188. for _, v := range d.Shape {
  189. s := xlsxShape{
  190. ID: "_x0000_s1025",
  191. Type: "#_x0000_t202",
  192. Style: "position:absolute;73.5pt;width:108pt;height:59.25pt;z-index:1;visibility:hidden",
  193. Fillcolor: "#fbf6d6",
  194. Strokecolor: "#edeaa1",
  195. Val: v.Val,
  196. }
  197. vml.Shape = append(vml.Shape, s)
  198. }
  199. }
  200. vml.Shape = append(vml.Shape, shape)
  201. f.VMLDrawing[drawingVML] = vml
  202. }
  203. // addComment provides a function to create chart as xl/comments%d.xml by
  204. // given cell and format sets.
  205. func (f *File) addComment(commentsXML, cell string, formatSet *formatComment) {
  206. a := formatSet.Author
  207. t := formatSet.Text
  208. if len(a) > 255 {
  209. a = a[0:255]
  210. }
  211. if len(t) > 32512 {
  212. t = t[0:32512]
  213. }
  214. comments := f.commentsReader(commentsXML)
  215. if comments == nil {
  216. comments = &xlsxComments{
  217. Authors: []xlsxAuthor{
  218. {
  219. Author: formatSet.Author,
  220. },
  221. },
  222. }
  223. }
  224. cmt := xlsxComment{
  225. Ref: cell,
  226. AuthorID: 0,
  227. Text: xlsxText{
  228. R: []xlsxR{
  229. {
  230. RPr: &xlsxRPr{
  231. B: " ",
  232. Sz: &attrValFloat{Val: 9},
  233. Color: &xlsxColor{
  234. Indexed: 81,
  235. },
  236. RFont: &attrValString{Val: "Calibri"},
  237. Family: &attrValInt{Val: 2},
  238. },
  239. T: a,
  240. },
  241. {
  242. RPr: &xlsxRPr{
  243. Sz: &attrValFloat{Val: 9},
  244. Color: &xlsxColor{
  245. Indexed: 81,
  246. },
  247. RFont: &attrValString{Val: "Calibri"},
  248. Family: &attrValInt{Val: 2},
  249. },
  250. T: t,
  251. },
  252. },
  253. },
  254. }
  255. comments.CommentList.Comment = append(comments.CommentList.Comment, cmt)
  256. f.Comments[commentsXML] = comments
  257. }
  258. // countComments provides a function to get comments files count storage in
  259. // the folder xl.
  260. func (f *File) countComments() int {
  261. count := 0
  262. for k := range f.XLSX {
  263. if strings.Contains(k, "xl/comments") {
  264. count++
  265. }
  266. }
  267. return count
  268. }
  269. // decodeVMLDrawingReader provides a function to get the pointer to the
  270. // structure after deserialization of xl/drawings/vmlDrawing%d.xml.
  271. func (f *File) decodeVMLDrawingReader(path string) *decodeVmlDrawing {
  272. if f.DecodeVMLDrawing[path] == nil {
  273. c, ok := f.XLSX[path]
  274. if ok {
  275. d := decodeVmlDrawing{}
  276. _ = xml.Unmarshal(namespaceStrictToTransitional(c), &d)
  277. f.DecodeVMLDrawing[path] = &d
  278. }
  279. }
  280. return f.DecodeVMLDrawing[path]
  281. }
  282. // vmlDrawingWriter provides a function to save xl/drawings/vmlDrawing%d.xml
  283. // after serialize structure.
  284. func (f *File) vmlDrawingWriter() {
  285. for path, vml := range f.VMLDrawing {
  286. if vml != nil {
  287. v, _ := xml.Marshal(vml)
  288. f.XLSX[path] = v
  289. }
  290. }
  291. }
  292. // commentsReader provides a function to get the pointer to the structure
  293. // after deserialization of xl/comments%d.xml.
  294. func (f *File) commentsReader(path string) *xlsxComments {
  295. if f.Comments[path] == nil {
  296. content, ok := f.XLSX[path]
  297. if ok {
  298. c := xlsxComments{}
  299. _ = xml.Unmarshal(namespaceStrictToTransitional(content), &c)
  300. f.Comments[path] = &c
  301. }
  302. }
  303. return f.Comments[path]
  304. }
  305. // commentsWriter provides a function to save xl/comments%d.xml after
  306. // serialize structure.
  307. func (f *File) commentsWriter() {
  308. for path, c := range f.Comments {
  309. if c != nil {
  310. v, _ := xml.Marshal(c)
  311. f.saveFileList(path, v)
  312. }
  313. }
  314. }