comment.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 := string(strings.Map(letterOnlyMapF, cell))
  112. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  113. xAxis := row - 1
  114. yAxis := TitleToNumber(col)
  115. vml := f.VMLDrawing[drawingVML]
  116. if vml == nil {
  117. vml = &vmlDrawing{
  118. XMLNSv: "urn:schemas-microsoft-com:vml",
  119. XMLNSo: "urn:schemas-microsoft-com:office:office",
  120. XMLNSx: "urn:schemas-microsoft-com:office:excel",
  121. XMLNSmv: "http://macVmlSchemaUri",
  122. Shapelayout: &xlsxShapelayout{
  123. Ext: "edit",
  124. IDmap: &xlsxIDmap{
  125. Ext: "edit",
  126. Data: commentID,
  127. },
  128. },
  129. Shapetype: &xlsxShapetype{
  130. ID: "_x0000_t202",
  131. Coordsize: "21600,21600",
  132. Spt: 202,
  133. Path: "m0,0l0,21600,21600,21600,21600,0xe",
  134. Stroke: &xlsxStroke{
  135. Joinstyle: "miter",
  136. },
  137. VPath: &vPath{
  138. Gradientshapeok: "t",
  139. Connecttype: "miter",
  140. },
  141. },
  142. }
  143. }
  144. sp := encodeShape{
  145. Fill: &vFill{
  146. Color2: "#fbfe82",
  147. Angle: -180,
  148. Type: "gradient",
  149. Fill: &oFill{
  150. Ext: "view",
  151. Type: "gradientUnscaled",
  152. },
  153. },
  154. Shadow: &vShadow{
  155. On: "t",
  156. Color: "black",
  157. Obscured: "t",
  158. },
  159. Path: &vPath{
  160. Connecttype: "none",
  161. },
  162. Textbox: &vTextbox{
  163. Style: "mso-direction-alt:auto",
  164. Div: &xlsxDiv{
  165. Style: "text-align:left",
  166. },
  167. },
  168. ClientData: &xClientData{
  169. ObjectType: "Note",
  170. Anchor: fmt.Sprintf(
  171. "%d, 23, %d, 0, %d, %d, %d, 5",
  172. 1+yAxis, 1+xAxis, 2+yAxis+lineCount, colCount+yAxis, 2+xAxis+lineCount),
  173. AutoFill: "True",
  174. Row: xAxis,
  175. Column: yAxis,
  176. },
  177. }
  178. s, _ := xml.Marshal(sp)
  179. shape := xlsxShape{
  180. ID: "_x0000_s1025",
  181. Type: "#_x0000_t202",
  182. Style: "position:absolute;73.5pt;width:108pt;height:59.25pt;z-index:1;visibility:hidden",
  183. Fillcolor: "#fbf6d6",
  184. Strokecolor: "#edeaa1",
  185. Val: string(s[13 : len(s)-14]),
  186. }
  187. d := f.decodeVMLDrawingReader(drawingVML)
  188. if d != nil {
  189. for _, v := range d.Shape {
  190. s := xlsxShape{
  191. ID: "_x0000_s1025",
  192. Type: "#_x0000_t202",
  193. Style: "position:absolute;73.5pt;width:108pt;height:59.25pt;z-index:1;visibility:hidden",
  194. Fillcolor: "#fbf6d6",
  195. Strokecolor: "#edeaa1",
  196. Val: v.Val,
  197. }
  198. vml.Shape = append(vml.Shape, s)
  199. }
  200. }
  201. vml.Shape = append(vml.Shape, shape)
  202. f.VMLDrawing[drawingVML] = vml
  203. }
  204. // addComment provides a function to create chart as xl/comments%d.xml by
  205. // given cell and format sets.
  206. func (f *File) addComment(commentsXML, cell string, formatSet *formatComment) {
  207. a := formatSet.Author
  208. t := formatSet.Text
  209. if len(a) > 255 {
  210. a = a[0:255]
  211. }
  212. if len(t) > 32512 {
  213. t = t[0:32512]
  214. }
  215. comments := f.commentsReader(commentsXML)
  216. if comments == nil {
  217. comments = &xlsxComments{
  218. Authors: []xlsxAuthor{
  219. {
  220. Author: formatSet.Author,
  221. },
  222. },
  223. }
  224. }
  225. cmt := xlsxComment{
  226. Ref: cell,
  227. AuthorID: 0,
  228. Text: xlsxText{
  229. R: []xlsxR{
  230. {
  231. RPr: &xlsxRPr{
  232. B: " ",
  233. Sz: &attrValFloat{Val: 9},
  234. Color: &xlsxColor{
  235. Indexed: 81,
  236. },
  237. RFont: &attrValString{Val: "Calibri"},
  238. Family: &attrValInt{Val: 2},
  239. },
  240. T: a,
  241. },
  242. {
  243. RPr: &xlsxRPr{
  244. Sz: &attrValFloat{Val: 9},
  245. Color: &xlsxColor{
  246. Indexed: 81,
  247. },
  248. RFont: &attrValString{Val: "Calibri"},
  249. Family: &attrValInt{Val: 2},
  250. },
  251. T: t,
  252. },
  253. },
  254. },
  255. }
  256. comments.CommentList.Comment = append(comments.CommentList.Comment, cmt)
  257. f.Comments[commentsXML] = comments
  258. }
  259. // countComments provides a function to get comments files count storage in
  260. // the folder xl.
  261. func (f *File) countComments() int {
  262. count := 0
  263. for k := range f.XLSX {
  264. if strings.Contains(k, "xl/comments") {
  265. count++
  266. }
  267. }
  268. return count
  269. }
  270. // decodeVMLDrawingReader provides a function to get the pointer to the
  271. // structure after deserialization of xl/drawings/vmlDrawing%d.xml.
  272. func (f *File) decodeVMLDrawingReader(path string) *decodeVmlDrawing {
  273. if f.DecodeVMLDrawing[path] == nil {
  274. c, ok := f.XLSX[path]
  275. if ok {
  276. d := decodeVmlDrawing{}
  277. _ = xml.Unmarshal(namespaceStrictToTransitional(c), &d)
  278. f.DecodeVMLDrawing[path] = &d
  279. }
  280. }
  281. return f.DecodeVMLDrawing[path]
  282. }
  283. // vmlDrawingWriter provides a function to save xl/drawings/vmlDrawing%d.xml
  284. // after serialize structure.
  285. func (f *File) vmlDrawingWriter() {
  286. for path, vml := range f.VMLDrawing {
  287. if vml != nil {
  288. v, _ := xml.Marshal(vml)
  289. f.XLSX[path] = v
  290. }
  291. }
  292. }
  293. // commentsReader provides a function to get the pointer to the structure
  294. // after deserialization of xl/comments%d.xml.
  295. func (f *File) commentsReader(path string) *xlsxComments {
  296. if f.Comments[path] == nil {
  297. content, ok := f.XLSX[path]
  298. if ok {
  299. c := xlsxComments{}
  300. _ = xml.Unmarshal(namespaceStrictToTransitional(content), &c)
  301. f.Comments[path] = &c
  302. }
  303. }
  304. return f.Comments[path]
  305. }
  306. // commentsWriter provides a function to save xl/comments%d.xml after
  307. // serialize structure.
  308. func (f *File) commentsWriter() {
  309. for path, c := range f.Comments {
  310. if c != nil {
  311. v, _ := xml.Marshal(c)
  312. f.saveFileList(path, v)
  313. }
  314. }
  315. }