comment.go 9.5 KB

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