comment.go 9.3 KB

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