comment.go 10.0 KB

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