comment.go 10.0 KB

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