comment.go 9.3 KB

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