comment.go 9.7 KB

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