comment.go 10 KB

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