comment.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. c, ok := f.XLSX["xl"+strings.TrimPrefix(f.getSheetComments(f.GetSheetIndex(n)), "..")]
  33. if ok {
  34. d := xlsxComments{}
  35. xml.Unmarshal([]byte(c), &d)
  36. sheetComments := []Comment{}
  37. for _, comment := range d.CommentList.Comment {
  38. sheetComment := Comment{}
  39. if comment.AuthorID < len(d.Authors) {
  40. sheetComment.Author = d.Authors[comment.AuthorID].Author
  41. }
  42. sheetComment.Ref = comment.Ref
  43. sheetComment.AuthorID = comment.AuthorID
  44. for _, text := range comment.Text.R {
  45. sheetComment.Text += text.T
  46. }
  47. sheetComments = append(sheetComments, sheetComment)
  48. }
  49. comments[n] = sheetComments
  50. }
  51. }
  52. return
  53. }
  54. // getSheetComments provides the method to get the target comment reference by
  55. // given worksheet index.
  56. func (f *File) getSheetComments(sheetID int) string {
  57. var rels = "xl/worksheets/_rels/sheet" + strconv.Itoa(sheetID) + ".xml.rels"
  58. var sheetRels xlsxWorkbookRels
  59. _ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(rels)), &sheetRels)
  60. for _, v := range sheetRels.Relationships {
  61. if v.Type == SourceRelationshipComments {
  62. return v.Target
  63. }
  64. }
  65. return ""
  66. }
  67. // AddComment provides the method to add comment in a sheet by given worksheet
  68. // index, cell and format set (such as author and text). Note that the max
  69. // author length is 255 and the max text length is 32512. For example, add a
  70. // comment in Sheet1!$A$30:
  71. //
  72. // xlsx.AddComment("Sheet1", "A30", `{"author":"Excelize: ","text":"This is a comment."}`)
  73. //
  74. func (f *File) AddComment(sheet, cell, format string) error {
  75. formatSet, err := parseFormatCommentsSet(format)
  76. if err != nil {
  77. return err
  78. }
  79. // Read sheet data.
  80. xlsx := f.workSheetReader(sheet)
  81. commentID := f.countComments() + 1
  82. drawingVML := "xl/drawings/vmlDrawing" + strconv.Itoa(commentID) + ".vml"
  83. sheetRelationshipsComments := "../comments" + strconv.Itoa(commentID) + ".xml"
  84. sheetRelationshipsDrawingVML := "../drawings/vmlDrawing" + strconv.Itoa(commentID) + ".vml"
  85. if xlsx.LegacyDrawing != nil {
  86. // The worksheet already has a comments relationships, use the relationships drawing ../drawings/vmlDrawing%d.vml.
  87. sheetRelationshipsDrawingVML = f.getSheetRelationshipsTargetByID(sheet, xlsx.LegacyDrawing.RID)
  88. commentID, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(sheetRelationshipsDrawingVML, "../drawings/vmlDrawing"), ".vml"))
  89. drawingVML = strings.Replace(sheetRelationshipsDrawingVML, "..", "xl", -1)
  90. } else {
  91. // Add first comment for given sheet.
  92. rID := f.addSheetRelationships(sheet, SourceRelationshipDrawingVML, sheetRelationshipsDrawingVML, "")
  93. f.addSheetRelationships(sheet, SourceRelationshipComments, sheetRelationshipsComments, "")
  94. f.addSheetLegacyDrawing(sheet, rID)
  95. }
  96. commentsXML := "xl/comments" + strconv.Itoa(commentID) + ".xml"
  97. f.addComment(commentsXML, cell, formatSet)
  98. var colCount int
  99. for i, l := range strings.Split(formatSet.Text, "\n") {
  100. if ll := len(l); ll > colCount {
  101. if i == 0 {
  102. ll += len(formatSet.Author)
  103. }
  104. colCount = ll
  105. }
  106. }
  107. f.addDrawingVML(commentID, drawingVML, cell, strings.Count(formatSet.Text, "\n")+1, colCount)
  108. f.addContentTypePart(commentID, "comments")
  109. return err
  110. }
  111. // addDrawingVML provides a function to create comment as
  112. // xl/drawings/vmlDrawing%d.vml by given commit ID and cell.
  113. func (f *File) addDrawingVML(commentID int, drawingVML, cell string, lineCount, colCount int) {
  114. col := string(strings.Map(letterOnlyMapF, cell))
  115. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  116. xAxis := row - 1
  117. yAxis := TitleToNumber(col)
  118. vml := vmlDrawing{
  119. XMLNSv: "urn:schemas-microsoft-com:vml",
  120. XMLNSo: "urn:schemas-microsoft-com:office:office",
  121. XMLNSx: "urn:schemas-microsoft-com:office:excel",
  122. XMLNSmv: "http://macVmlSchemaUri",
  123. Shapelayout: &xlsxShapelayout{
  124. Ext: "edit",
  125. IDmap: &xlsxIDmap{
  126. Ext: "edit",
  127. Data: commentID,
  128. },
  129. },
  130. Shapetype: &xlsxShapetype{
  131. ID: "_x0000_t202",
  132. Coordsize: "21600,21600",
  133. Spt: 202,
  134. Path: "m0,0l0,21600,21600,21600,21600,0xe",
  135. Stroke: &xlsxStroke{
  136. Joinstyle: "miter",
  137. },
  138. VPath: &vPath{
  139. Gradientshapeok: "t",
  140. Connecttype: "miter",
  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. c, ok := f.XLSX[drawingVML]
  188. if ok {
  189. d := decodeVmlDrawing{}
  190. _ = xml.Unmarshal(namespaceStrictToTransitional(c), &d)
  191. for _, v := range d.Shape {
  192. s := xlsxShape{
  193. ID: "_x0000_s1025",
  194. Type: "#_x0000_t202",
  195. Style: "position:absolute;73.5pt;width:108pt;height:59.25pt;z-index:1;visibility:hidden",
  196. Fillcolor: "#fbf6d6",
  197. Strokecolor: "#edeaa1",
  198. Val: v.Val,
  199. }
  200. vml.Shape = append(vml.Shape, s)
  201. }
  202. }
  203. vml.Shape = append(vml.Shape, shape)
  204. v, _ := xml.Marshal(vml)
  205. f.XLSX[drawingVML] = v
  206. }
  207. // addComment provides a function to create chart as xl/comments%d.xml by
  208. // given cell and format sets.
  209. func (f *File) addComment(commentsXML, cell string, formatSet *formatComment) {
  210. a := formatSet.Author
  211. t := formatSet.Text
  212. if len(a) > 255 {
  213. a = a[0:255]
  214. }
  215. if len(t) > 32512 {
  216. t = t[0:32512]
  217. }
  218. comments := xlsxComments{
  219. Authors: []xlsxAuthor{
  220. {
  221. Author: formatSet.Author,
  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. c, ok := f.XLSX[commentsXML]
  257. if ok {
  258. d := xlsxComments{}
  259. _ = xml.Unmarshal(namespaceStrictToTransitional(c), &d)
  260. comments.CommentList.Comment = append(comments.CommentList.Comment, d.CommentList.Comment...)
  261. }
  262. comments.CommentList.Comment = append(comments.CommentList.Comment, cmt)
  263. v, _ := xml.Marshal(comments)
  264. f.saveFileList(commentsXML, v)
  265. }
  266. // countComments provides a function to get comments files count storage in
  267. // the folder xl.
  268. func (f *File) countComments() int {
  269. count := 0
  270. for k := range f.XLSX {
  271. if strings.Contains(k, "xl/comments") {
  272. count++
  273. }
  274. }
  275. return count
  276. }