comment.go 9.3 KB

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